Learning C++: returning references AND getting around slicing

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

提交回复
热议问题