Boost Shared Ptr

The boost::shared_ptr<> class template is a member of the BoostLibraries. It emulates a pointer with reference-counted semantics. You can use it just like a normal pointer, but as soon as the last reference to the object goes out of scope, the object is automatically deleted.

In order to be ThreadSafe, shared_ptr<> incurs high overhead on some architectures.

http://www.boost.org/libs/smart_ptr/smart_ptr.htm

There is a companion class to shared_ptr<> called weak_ptr<>. A weak_ptr<> can be formed from a shared_ptr<> and vice versa, but a weak_ptr<> cannot be used directly, does not influence the lifetime of the pointed-to object, and is set to null when the object is deleted. This is useful when you have child nodes in a tree-like structure that need to refer back to their parent. When the parent is destroyed, you expect the children to be destroyed, and this would not happen if the child held a "strong" reference back to the parent.

Boost's implementation of shared_ptr and weak_ptr have been accepted as part of TechnicalReportOne. This doesn't automatically mean that they will be added to the standard library, but it seems likely.
I'm curious about the shared_ptr - is cleanup lazy, or does it support ResourceAcquisitionIsInitialization? That is, does the object get deleted the moment the shared_ptr falls off the stack? I've been programming in C# and Python, and find myself missing the simple semantics of RAII in those languages. I'm just curious how well it works with the shared_ptr<>? If not, can one use auto_ptr with weak_ptr?

You can do RAII with them -- shared_ptr will immediately delete your object through shared_ptr::~shared_ptr as you'd expect. AFAIK though, you can't mix and match shared_ptr/weak_ptr with auto_ptr [ you can transfer ownership from auto_ptr to shared_ptr, however]. In C#, you can use the 'using' keyword for similar effect, but you probably knew about that.

Leaving aside that 'using' keyword is explicit, it still can't be applied to class members, so you must write Dispose methods manually to do what C++ compiler does automatically on destruction.


CategoryBoost CategoryCpp

EditText of this page (last edited September 1, 2010) or FindPage with title or text search