Will auto_ptr protect against this?

I do not quite understand if auto_ptr helps 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 myA._member link myA._member valid if smart leaves its scope? If auto_ptr is not the answer here, what is it?

EDIT: I see where I embarrassed everyone; I have to get myA back out of scope, so I take care that the member is really valid after smart goes out of scope.

+4
source share
3 answers

This will not help. _member will become a dangling pen. This is because auto_ptr guarantees destruction at the end of the scope: no more and no less.

There are 2 possible answers.

  • You can create the type _member boost::shared_ptr<const B> .
  • Alternatively, if class B is small , copyable , monomorphic , and the object identifier does not need to be saved , you can make _member a value and save a copy of the argument there. This is by far the easiest option, but obviously it is very limited.

In response to your editing: This is indeed the case I spoke of. By returning myA by value, a copy is created, and the _member instance refers to the already destroyed local one. As described, both shared_ptr and value semantics solve this problem.

+6
source

The auto_ptr class is a wrapper over regular pointers. They take care of de-allocation when the stack is unwound (the auto_ptr destructor is called, which in turn frees up your contained object).

Note that your object A also being created on the stack. When the scope ends, both A and auto_ptr will be freed. Other than that, trying to access object A will give you a compile-time error.

Assuming object A was created somewhere outside the block, then you have a real problem. Since object A stores the link for object B , outside the block area, this link becomes invalid.

Note also that with C ++ 0x auto_ptr deprecated. Use unique_ptr . Take a look at the "General Purpose Smart Pointers" that come to you in C ++ 0x.

+2
source
 { auto_ptr<B> smart(new B()); A myA(*smart); } 

Both pointers held in the smart and the myA object will be destroyed at the end of this area. But that should be what you want with this snipit code.

As soon as the region ends, myA will be destroyed first (its last declared).
Then after that smart will be destroyed, and its destructor will delete the pointer.

Since there is no way to refer to smart or mine, I hope you want to remove poiner at this point.

Alternatively, you can do this:

 { B myB; A myA(myB); } 
0
source

All Articles