[shared_ptr] Is it possible for a shared_ptr to hand over it ownership

hello all I hope this is not a stupid question. Suppose I have a shared_ptr which is the only owner of the pointee. I hope there is a way to hand over its ownership to another object without rendering the pointee being deleted. Or, if the answer is no, is there an alternative class that has this feature? The use case is like this: B b; { shared_ptr p1(A()), p2(A()); b.GetOwnership(p1.HandOver()); // now p1 is empty } // p2 is deleted here // but the A obj p1 used to be pointing to // has been handed over to b and is still // alive here b.DestroyA(); // the A obj holded by b is destroyed by b // explicitly Thanks in advance B/Rgds Max ------------------------------------------------------------------- 新浪空间——与朋友开心分享网络新生活!(http://space.sina.com.cn/ )

On Thu, Dec 25, 2008 at 4:57 AM, Max
Suppose I have a shared_ptr which is the only owner of the pointee. I hope there is a way to hand over its ownership to another object without rendering the pointee being deleted.
Or, if the answer is no, is there an alternative class that has this feature?
The use case is like this:
B b; { shared_ptr p1(A()), p2(A());
b.GetOwnership(p1.HandOver()); // now p1 is empty }
That's not possible because in general shared_ptr can use custom deleters and/or aliasing which B can't deal with, unless it's shared_ptr itself. :) Consider: boost::shared_ptr<FILE> open_file( char const * name, char const * mode ) { if( FILE * f=fopen(name,mode) ) return boost::shared_ptr<FILE>(f,fclose); else boost::throw_exception(file_open_error()); } Emil Dotchevski Reverge Studios, Inc. http://www.revergestudios.com/reblog/index.php?n=ReCode

Have you tried using auto_ptr? It forces the right-hand side of the assignment to give up ownership. boost::shared_ptr<A> p1(new A()); std::auto_ptr<A> p2; p2 = p1; //p1 is now null and p2 points to what p1 was pointing to Hope this works! I haven't tested this and my C++/Boost/STL is very shaky due to disuse. Ben
participants (3)
-
Benjamin Lau
-
Emil Dotchevski
-
Max