Saturday, August 24, 2013

boost::shared_ptr



Reference:

Shared pointer is a smart pointer (a C++ object wih overloaded operator*() and operator->()) that keeps a pointer to an object and a pointer to a shared reference count. Every time a copy of the smart pointer is made using the copy constructor, the reference count is incremented. When a shared pointer is destroyed, the reference count for its object is decremented. Shared pointers constructed from raw pointers initially have a reference count of 1. When the reference count reaches 0, the pointed object is destroyed, and the memory it occupies is freed. You do not need to explicitly destroy objects: it will be done automatically when the last pointer's destructor runs.

Usage

When creating a new object with new, use it as a constructor argument of a boost::shared_ptr.
boost::shared_ptr foo_ptr(new Foo());
You can reassign the pointer to a new object using the member function reset(). This will decrease the reference count of the old object, if any, and reinitialize the object with the argument and a reference count of 1.
foo_ptr.reset(new Foo());
Note however that you cannot obtain a shared pointer to an object from a raw pointer. This will cause a segmentation fault:
void some_function(Foo *f) {
   boost::shared_ptr fptr(f);
   fptr->something();
}
...
Foo *foo = new Foo();
some_function(foo);
foo->something();
That's because the temporary fptr is initialized with a reference count of 1. After the function returns, the reference count is zero and the object is destroyed. foo->something() will then fail, because foo no longer points to a valid object.
An uninitialized shared pointer is empty. This is equivalent to NULL for raw pointers. You can check for an empty shared pointer using this code:
if (foo) {
   // foo points to an object
} else {
   // foo is empty
}
A raw pointer can be retrieved using the get() method.
Foo *rawptr = fptr.get();

No comments:

Post a Comment