Learning C++: returning references AND getting around slicing

前端 未结 8 1389
醉酒成梦
醉酒成梦 2021-02-14 00:06

I\'m having a devil of a time understanding references. Consider the following code:

class Animal
{
public:
    virtual void makeSound() {cout << \"rawr\"         


        
8条回答
  •  鱼传尺愫
    2021-02-14 00:39

    1) If you're creating new objects, you never want to return a reference (see your own comment on #3.) You can return a pointer (possibly wrapped by std::shared_ptr or std::auto_ptr). (You could also return by copy, but this is incompatible with using the new operator; it's also slightly incompatible with polymorphism.)

    2) rFunc is just wrong. Don't do that. If you used new to create the object, then return it through an (optionally wrapped) pointer.

    3) You're not supposed to. That is what pointers are for.


    EDIT (responding to your update:) It's hard to picture the scenario you're describing. Would it be more accurate to say that the returned pointer may be invalid once the caller makes a call to some other (specific) method?

    I'd advise against using such a model, but if you absolutely must do this, and you must enforce this in your API, then you probably need to add a level of indirection, or even two. Example: Wrap the real object in a reference-counted object which contains the real pointer. The reference-counted object's pointer is set to null when the real object is deleted. This is ugly. (There may be better ways to do it, but they may still be ugly.)

提交回复
热议问题