Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) new

 

C++ keyword to dynamically allocate memory and returning a pointer to this memory location. If the allocation of memory fails, std::bad_alloc is thrown and a pointer to null is returned.

 

When the pointer is no longer needed, delete must be called.

 

Prefer the use of std::auto_ptr (or other smart pointers) over the use of plain pointers [1][2].

 

 

 

 

 

Example with simple class

 

int main()
{
  const MyClass * const p = new MyClass; //Bad practice
  //Use p
  delete p; //Do not forget to delete p
}

 

 

 

 

 

Example with base and derived class

 

Suppose you have a base class called Animal and a derived class called Monkey. Then you can store a Monkey as an Animal in the following way.

 

int main()
{
  const Animal * const p = new Monkey; //Bad practice
  //Use the Animal interface of p (p does not know it is monkey anymore)
  delete p; //Do not forget to delete p
}

 

 

 

 

 

Example with base and derived class using std::auto_ptr

 

Prefer the use of std::auto_ptr (or other smart pointers) over the use of plain pointers [1-3].

 

#include <memory>

int main()
{
  const std::auto_ptr<Animal> p = new Monkey;
  //Use the Animal interface of p (p does not know it is monkey anymore)
  //std::auto_ptr deletes p automatically
}

 

 

 

 

 

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