Boost Shared Pointer
Smart pointer is an abstract data type that has all features of a standard but also provides automatic garbage collection. Smart pointers facilitate the dynamic memory operations. Their main advantage is reducing memory leaks and bugs due to poor memory management.
Indrodcution to Boost Smart Pointers
Boost C++ Libraries are a collection of open source libraries that extend the functionality of C++ with varity of features including smart pointers. Boost smart pointers follow the ideas described by Bjarne Stroustrup at "The C++ Programming Language", 3rd edition known as "resource acquisition is initialization". The Boost smart pointer library provides six different types:
Operator delete must not be called to release resources when smart pointers are used.
The shared_ptr is a template class that stores a dynamically allocated object. It differs to the other five types because object ownerships is shared among multiple pointers. Every shared_ptr meets the requirements of STL and can be used with any of its classes includind containers such as vector, deque, list, map, set, etc. To use shared_ptr file boost/shared_ptr.hpp should be included.
The example contains a simple demostration of the shared_ptr. Class Student which stores a name and id of a student is declared and defined. The shared_ptr is a template class so at the example a type has been defined which is a shared_ptr of our class Student. It is important to note that at the destructor the message Elvis has left the building. is displayed. A share_ptr is created at main, operator delete is not used (and must not be used) and at the end of the execution of the program the destructor is automatically called so the message is printed.
Student(std::string sName, std::string sId);
std::string getName() const;
std::string getId() const;
Student::Student(std::string sName, std::string sId) :
//Everything has been init
//Nothing to do
std::cout << "Elvis has left the building." << std::endl;
std::string Student::getName() const
std::string Student::getId() const
typedef boost::shared_ptr<Student> StudentPtr;
StudentPtr pStudent( new Student("Leon Anavi", "F010203") );
std::cout << "Student: " << pStudent->getName() << " "
<< pStudent->getId() << std::endl;
[leon@localhost shrptr]$ g++ shrptr_test.cpp -o shrptr_test
[leon@localhost shrptr]$ ./shrptr_test
Student: Leon Anavi F010203
Elvis has left the building.
Boost Smart Pointers
Boost shared_ptr class template