Learning C++: returning references AND getting around slicing

前端 未结 8 1374
醉酒成梦
醉酒成梦 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

    If you want to return a polymorphic type from a method and don't want to assign it on the heap you could consider making it a field in that method's class and making the function to return a pointer to it of whatever base class you want.

    0 讨论(0)
  • 2021-02-14 00:42

    If I pass back a pointer how do I communicate to the programmer that the pointer is not theirs to delete if this is the case? Or alternatively how do I communicate that the pointer is subject to deletion at any time (from the same thread but a different function) so that the calling function should not store it, if this is the case.

    If you really can't trust the user, then don't give them a pointer at all: pass back an integer-type handle and expose a C-style interface (e.g., you have a vector of instances on your side of the fence, and you expose a function that takes the integer as the first parameter, indexes into the vector and calls a member function). That's the old-fashioned way (notwithstanding that we didn't always have fancy things like "member functions" ;) ).

    Otherwise, try using a smart pointer with appropriate semantics. Nobody sane would ever think that delete &*some_boost_shared_ptr; is a good idea.

    0 讨论(0)
提交回复
热议问题