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

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
VNarasimhaM
  • 1,460
  • 3
  • 22
  • 36

2 Answers2

6

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
  • 733,204
  • 149
  • 1,241
  • 1,454
3

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
  • 54,333
  • 19
  • 131
  • 194