tags:

views:

76

answers:

2

Hi,

I have a code which looks like this:

class Parent
{
 auto_ptr<Resource> ptr2Resc;
 public: void parentMethod(int i )
{
 SomeOtherClass someOthrPtr = new SomeOtherClass(ptr2Resc); 
}
};

The ctor of SomeOtherClass:
SomeOtherClass(auto_ptr<Resource> ptrRes);

So now when i call parentMethod, the auto_ptr gets swapped and the ptr2Resc is dellocated. My C++ code doesn't support TR1 or Boost. So whats the best way to have the ptr2Resc deallocated during the Parent Class destructor, and not when it is passed as a parameter. Can i pass it as a reference to auto_ptr to the SomeOtherClass ctor?

Thanks

+1  A: 

std::auto_ptr<Resource> has an ugly copy constructor. Make copy of the boost::shared_ptr implementation and use it (your copy).

Alexey Malistov
+3  A: 

Following is the quote from Josuttis book regarding passing auto_ptr by reference:

You might think about passing auto_ptrs by reference instead. However, passing auto_ptrs by reference confuses the concept of ownership. A function that gets an auto_ptr by reference might or might not transfer ownership. Allowing an auto_ptr to pass by reference is very bad design and you should always avoid it

As I said in my comment, if you do not intend to transfer the ownnership, you can simply change the constructor of SomeClass to take a raw pointer.

Naveen
Changing it to raw pointer is what i intended to do. But i wanted to see if its okay for passing it as reference.
No don't do it..today it might work..but if tomorrow somebody creates a local copy of the passed auto_ptr reference you will be in trouble.
Naveen