More in detail, a weak pointer is associated to a shared pointer. Whenever someone needs to access the contents of a weak pointer, the weak pointer must first be converted to a shared pointer by means of the lock method or a special constructor. If the object managed by the shared pointer goes away, any further conversion from the weak pointer to a shared pointer will fail.

Here is a fictitious example in which the use of a weak pointer might be useful. A shared pointer is accessed by two threads. thread1 should be able to release the object, but the object should be accessible at some point in thread2 only if it still exists. Using the weak pointer makes this situation possible without using a complex locking protocol:

Intrusive pointers

The intrusive pointer is a light version of the shared pointer. It assumes that the dynamically allocated object it has to point to implements a reference counter by itself. This maintains the counter in a single place and keeps the smart pointer to the minimum size (the size of the raw pointer).

In order to define an intrusive pointer for a given object, you must first create two functions that manage its embedded reference counter. One is intrusive_ptr_add_ref, which simply increases the counter; the other is intrusive_ptr_release, which decreases the counter and, if it reaches zero, releases the object.

This is much clearer with an example. You may want to assume that some_resource is a class you have written or a class provided by someone else, perhaps even the operating system itself.

Conclusion

I discovered smart pointers a year ago, and since then I firmly believe that their use makes code safer, more robust, and easier to read. I can no longer conceive any C++ code that directly manages dynamically allocated objects due to all the problems that can arise.

Now that you have finished this article, I hope you feel similarly and that from now on you will use these techniques to improve your own programs.