tags:

views:

138

answers:

2

I have a class like this:

class A 
{

 private:

 B* ptr;

}

But B ptr is shared among different A objects. How can I use auto_ptr so that when A gets destructed B stays on so that other A objects that point to the same ptr can continue without issues. Does this look ok:

class A
{
public:

 auto_ptr< B > m_Ptr;

private:

 B* ptr;

}

what are the different ways people have implemented this and any issues/advantages they saw one to another... Thanks

+6  A: 

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

This is a part of the BOOST library though and not STL so it may not be available on your particular platform. However if you google around a bit you can find a lot of standalone refcounted pointer implementations that will satisfy your needs here.

JaredPar
+3  A: 

If I'm understanding 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. The boost thing is basically the same. I would recommend using the TR1 version if you have it because all C++ compilers are supposed to support TR1 where boost is an add-on library you might not be able to find everywhere.

Omnifarious