Having mostly been a C programmer, I’ve not kept up with C++ very much. Lately, though, I’ve been using it, and with the final adoption of the C++0x standard, I’ve started looking into the new features. Here’s one that caught my eye this morning:
shared_ptr from section 126.96.36.199 of the C++0x standard.
To users of the Boost libraries, this will be old hat, but to me its quite new and exciting.
shared_ptr is a class template that embodies a pointer that can be shared among different users such that when the last reference to the shared pointer is destroyed, the pointed to object is also destroyed. In effect, it is a sort of reference counted pointer. The upshot of this is that you can allocate memory with
new, assigning the result to a
shared_ptr, and then never have to worry about calling
Here’s an example:
"Constructor: C""Destructor : C""Constructor: B""Destructor : B"
This example compiles under GNU g++, but I’ve not tested it with any other compilers, some of which don’t have as good support for C++0x yet. You’ll need to use the –std=c++0x or –std=gnu++0x compiler options.
g++ --std=c++0x -o shared_ptr shared_ptr.cpp
If you compiler supports
shared_ptr, try running this example. On my system it produces the following output:eris@luthien:/vol0/eris/dev/study/c++/shared_ptr $ g++ --std=c++0x -o shared_ptr shared_ptr.cpp && ./shared_ptr Constructor: B Constructor: C Destructor : B
Ahas two members, a
Band a regular pointer to class
C. Both are allocated with
A‘s constructor, but neither of them is ever explicitly
Ahas no destructor at all. But the messages printed by the constructors and destructors of
Clet us see that the
Bobject – held through a
shared_ptr– does get it’s destructor called when the program terminates, while the
C– held through a regular pointer – does not.
C‘s memory has leaked through the programmer “forgetting” to define a destructor for
A, but the
Btakes care of it’s deletion for us.
In other words, a
shared_ptrsaves us from having to write a destructor, and helps to prevent our feet from being shot.