Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) Smart pointer

 

A smart pointer is a container that manages a pointer. Prefer to use smart pointers over normal pointers [1-3].

 

Boost.Smart_ptr is the Boost smart pointer library.

 

 

 

 

 

List of smart pointers (incomplete)

 

 

 

 

 

 

Boost 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>
#include <boost/shared_ptr.hpp>

struct Test
{
  Test(const int x) : m_x(x) {}
  const int m_x;
};

int main()
{
  {
    boost::shared_ptr<Test> p;
    p->m_x; //Good: uninitialized pointer detected by Boost
  }
  {
    boost::scoped_ptr<Test> p;
    p->m_x; //Good: uninitialized pointer detected by Boost
  }
}

 

The code below shows that initializing a boost::shared_ptr with null will not be easy, but even when it succeeds, boost::shared_ptr will check itself for null. A boost::scoped_ptr can be null, but will check itself for it as well.

 

#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>

struct Test
{
  Test(const int x) : m_x(x) {}
  const int m_x;
};

Test * CreateNullPointer() { return 0; }

int main()
{
  {
    boost::shared_ptr<Test> p;
    //p.reset(0); //Good: does not compile: 0 is an integer
    //p.reset(NULL); //Good: does not compile
    p.reset(CreateNullPointer()); //Bad: tricked the compiler
    //p->m_x; //Good: uninitialized pointer detected by Boost
  }
  {
    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

 

  1. Scott Meyers. Effective C++ (3rd edition). ISBN: 0-321-33487-6. Item 13: 'Use objects to manage resources'.
  2. Scott Meyers. Effective C++ (3rd edition). ISBN: 0-321-33487-6. Item 17: 'Store newed objects in smart pointers in standalone statements'
  3. Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6. Chapter 13: 'Ensure resources are owned by objects. Use explicit RAII and smart pointers.

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict