How can I use auto_ptr as a member variable that handles another member variable

I have a class like this:

class A 
{

 private:

 B* ptr;

}

      

But B's ptr is shared between different objects of A. How can I use auto_ptr so that when A is destroyed, B stays on, so that other objects of A pointing to the same ptr can continue without issue. This looks ok:

class A
{
public:

 auto_ptr< B > m_Ptr;

private:

 B* ptr;

}

      

What are the different ways people have implemented this and any challenges / benefits they saw to each other ... Thanks

+2


source to share


2 answers


What you are looking for is shared_ptr. It handles exactly this type of scenario.



It is part of the BOOST library, although not STL, so it may not be available on your specific platform. However, if you're a bit like Google, you can find a variety of standalone refcounted pointers to suit your needs here.

+6


source


If I understand your question clearly, I would recommend using ::std::tr1::shared_ptr

or ::boost::shared_ptr

.



This article is a good tutorial on shared_ptr in TR1 . Acceleration is basically the same thing. I would recommend using the TR1 version if you have that, because all C ++ compilers need to support TR1, where boost is an extra library that you might not be able to find all over the place.

+3


source







All Articles