When to use the new-Operator in C++

During my C++ studies, there have been a bunch of questions which came up related to proper memory management, passing data structures and so long. One question was, when to use the new-Operator to instantiate for example a class and when not.

Basically, you should use the new-Operator when you want to make sure, that the object still exists after leaving scope.

Let’s have a look at this code:

void foo()
{
Point p = Point(0,0);
} // p is now destroyed.
 
for (...)
{
Point p = Point(0,0);
} // p is destroyed after each loop
 
class Foo
{
 
Point p;
}; // p will be automatically destroyed when foo is.

If you want to make sure, your objects survives when leaving scope, use then new operator, like this:

void SomeFunc2()
{
Point *p1 = new Point(0,0);
delete p1; // p1 is leaked unless it gets deleted
}

Please note that when you instantiate a type with the new-Operator, you have to manually free this memory, as soon as it is no more used. Also, memory allocation using new is more expensive in terms of time than if they are allocated in-place.

You can, for example, instantiate a type inside a method using new-Operator and then pass the object using a pointer to a method not in scope of the current method.

Types instantiated using new are allocated on the heap memory.

Leave a Reply

Your email address will not be published. Required fields are marked *

*