I am not quite clear if auto_ptr will help me in this case:
class A { A(const B& member) : _member(B) {}; ... const B& _member; }; A generateA() { auto_ptr<B> smart(new B()); A myA(*smart); return myA; }
Will the myA._member reference be valid when smart leaves its enclosing scope? If auto_ptr isn’t the answer here, what is?
EDIT: I see where I confused everyone; I have to return myA outside the scope, which is why I care about _member being valid after smart exits the scope.
It won’t help you. _member will become a dangling handle. This is because
auto_ptrguarantees destruction at end of scope: no more, and no less.There are 2 possible answers.
boost::shared_ptr<const B>.In response to your edit: That is indeed the case that I was talking about. By returning myA by value, a copy is created, and the copy’s _member refers to the already destructed local. As described, both
shared_ptrand value semantics solve this.