Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) pointer

 

A pointer is a type that holds an address.

 

When a pointer is uninitialized, it should point to NULL. You initialize a pointer using new, which reserves free space for the dynamically allocated instance and returns the address to it.

 

C++ does not free this memory on its own. Therefore, you have to call delete to do so.

 

Reading/writing from/to an uninitialized pointer results in an access violation.

 

Prefer using a smart pointer over a plain pointer [1-3], e.g. use an std::auto_ptr or boost::shared_ptr. Use 0 rather than NULL [4].

 

Avoid non-trivial pointer arithmetic [5].

 

 

 

 

 

Example with plain pointer

 

struct MyClass { /* some class definition */ };

int main()
{
  MyClass * pClass = new MyClass;
  pClass->doStuff();
  delete pClass
}

 

 

 

 

 

Example with std::auto_ptr

 

#include <memory>

struct MyClass { /* some class definition */ };

int main()
{
  const std::auto_ptr<MyClass> pClass(new MyClass);
  pClass->doStuff(); //Hey, the same way of accessing the pointed instance!
  //Done, std::auto_ptr deletes itself when going out of scope
}

 

 

 

 

 

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.
  4. Bjarne Stroustrup. The C++ Programming Language (3rd edition). 1997. ISBN: 0-201-88954-4. Section 5.8.3: 'Use 0 rather than NULL'.
  5. Bjarne Stroustrup. The C++ Programming Language (3rd edition). 1997. ISBN: 0-201-88954-4. Section 5.8.1: 'Avoid non-trivial pointer arithmetic'.

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict