When to use "new" and when not to, in C++? [duplicate]
Asked Answered
R

4

129

Possible Duplicate:
When should I use the new keyword in C++?

When should I use the "new" operator in C++? I'm coming from C#/Java background and instantiating objects is confusing for me.

If I've created a simple class called "Point", when I create a point should I:

Point p1 = Point(0,0);

or

Point* p1 = new Point(0, 0);

Can someone clarify for me when to use the new operator and when not to?

Duplicate of:

When should I use the new keyword in C++?

Related:

About constructors/destructors and new/delete operators in C++ for custom objects

Proper stack and heap usage in C++?

Rhizopod answered 24/3, 2009 at 22:53 Comment(2)
duplicate - too many times to countExcitation
as Neil said, this has been asked countless number of times.Highhanded
E
184

You should use new when you wish an object to remain in existence until you delete it. If you do not use new then the object will be destroyed when it goes out of scope. Some examples of this are:

void foo()
{
  Point p = Point(0,0);
} // p is now destroyed.

for (...)
{
  Point p = Point(0,0);
} // p is destroyed after each loop

Some people will say that the use of new decides whether your object is on the heap or the stack, but that is only true of variables declared within functions.

In the example below the location of 'p' will be where its containing object, Foo, is allocated. I prefer to call this 'in-place' allocation.

class Foo
{

  Point p;
}; // p will be automatically destroyed when foo is.

Allocating (and freeing) objects with the use of new is far more expensive than if they are allocated in-place so its use should be restricted to where necessary.

A second example of when to allocate via new is for arrays. You cannot* change the size of an in-place or stack array at run-time so where you need an array of undetermined size it must be allocated via new.

E.g.

void foo(int size)
{
   Point* pointArray = new Point[size];
   ...
   delete [] pointArray;
}

(*pre-emptive nitpicking - yes, there are extensions that allow variable sized stack allocations).

Emmen answered 24/3, 2009 at 22:56 Comment(4)
+1 Just remember you need to manually delete the new'ed pointer delete p1;Electrolyze
+1 nice one. just remember the first one can be written as Point p(0, 0); too. the = .. syntax may make him think that p is somehow a pointer that's assigned something.Padding
@Andrew Grant If you must use new use shared_ptr or unique_prt. that were introduced in c++11 STL <memory> shared pointers will do book keeping of delete automatically. note for arrays default deleter provided by shared_ptr calls delete, not delete[] therefore use lambda functions std::shared_ptr<int> p(new int[10], [](int* p) { delete[] p; }); or std::shared_ptr<int> p(new int[10], std::default_delete<int[]>()); or using helper provided from unique_ptr which calls delete[] std::unique_ptr<int,void(*)(int*)> p(new int[10], [](int* p) { delete[] p; });Gailey
This answer is more than 10 years old. Shouldn't it now be "you never use `new', between RAII and smart pointers it is never needed"?Aalesund
A
13

Take a look at this question and this question for some good answers on C++ object instantiation.

This basic idea is that objects instantiated on the heap (using new) need to be cleaned up manually, those instantiated on the stack (without new) are automatically cleaned up when they go out of scope.

void SomeFunc()
{
    Point p1 = Point(0,0);
} // p1 is automatically freed

void SomeFunc2()
{
    Point *p1 = new Point(0,0);
    delete p1; // p1 is leaked unless it gets deleted
}
Allineallis answered 24/3, 2009 at 22:57 Comment(0)
T
4

You should use new when you want an object to be created on the heap instead of the stack. This allows an object to be accessed from outside the current function or procedure, through the aid of pointers.

It might be of use to you to look up pointers and memory management in C++ since these are things you are unlikely to have come across in other languages.

Turnbow answered 24/3, 2009 at 22:58 Comment(1)
New does not guarantee heap allocation and simply avoiding new does not guarantee stack allocation.Diactinic
P
3

New is always used to allocate dynamic memory, which then has to be freed.

By doing the first option, that memory will be automagically freed when scope is lost.

Point p1 = Point(0,0); //This is if you want to be safe and don't want to keep the memory outside this function.

Point* p2 = new Point(0, 0); //This must be freed manually. with...
delete p2;
Pasquale answered 24/3, 2009 at 22:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.