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.

 

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 [0][1].

 

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 [0][1].

 

 

#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

[0]  Bjarne Stroustrup. The C++ Programming Language (3rd edition).ISBN: 0-201-88954-4

[1]  Herb Sutter and Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6

 

 

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

Go back to Richel Bilderbeek's homepage.