(C++) boost::scoped\_ptr
January 11, 2018 · View on GitHub
(C++) boost::scoped_ptr
boost::scoped_ptr is a smart pointer that deletes the instance it points to when going out of scope.
boost::scoped_ptr is similar to std::unique_ptr (C++11) and std::auto_ptr (C++98, depreciated in C++11).
#include <boost/scoped_ptr.hpp> int main() { const boost::scoped_ptr<MyClass> p(new MyClass); p->doStuff(); //Hey, the same way of accessing the pointed instance! //Done, boost::scoped_ptr deletes itself when going out of scope }
Smart pointers and null
Boost smart pointers check for null themselves, so there is no need to check these to be inititialized. In the example below a member variable of a class is requested from an unitialized smart pointer. The program will abort and the runtime error will be shown.
#include <boost/scoped_ptr.hpp> struct Test { Test(const int x) : m_x(x) {} const int m_x; }; int main() { boost::scoped_ptr<Test> p; p->m_x; //Good: uninitialized pointer detected by Boost }
A boost::scoped_ptr can be null, but will check itself for it:
#include <boost/scoped_ptr.hpp> struct Test { Test(const int x) : m_x(x) {} const int m_x; }; Test * CreateNullPointer() { return 0; } int main() { boost::scoped_ptr<Test> p; p.reset(0); //Valid: boost::scoped_ptr can be empty p.reset(CreateNullPointer()); //Valid: boost::scoped_ptr can be empty p->m_x; //Good: uninitialized pointer detected by Boost }
References
- Scott Meyers. Effective C++ (3rd edition). ISBN:0-321-33487-6. 2005. Item 13: 'Use objects to manage resources'
- Scott Meyers. Effective C++ (3rd edition). ISBN:0-321-33487-6. 2005. Item 17: 'Store newed objects in smart pointers in standalone statements'