开发者

Handling a resource effectively using auto pointers

开发者 https://www.devze.com 2022-12-12 05:00 出处:网络
I have a code which looks like this: class Parent { auto_ptr<Resource> ptr2Resc; public: void parentMethod(int i )

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 C开发者_Go百科lass 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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消