You must use new if you want the object to remain in place until you delete it. If you are not using new , then the object will be destroyed when it goes beyond the scope. Here are some examples:
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 using new determines whether your object is on the heap or the stack, but this is only true for variables declared inside functions.
In the example below, the location of "p" will be where its containing Foo object is highlighted. I prefer to call this distribution "in place."
class Foo { Point p; };
Allocating (and freeing) objects using new much more expensive than if they are allocated in place, so its use should be limited where necessary.
The second example, when allocating through new is for arrays. You cannot * resize the array in place or stack at run time, so when you need an array of undefined size, it must be assigned through a new one.
eg.
void foo(int size) { Point* pointArray = new Point[size]; ... delete [] pointArray; }
(* pre-emptive nitpicking - yes, there are extensions that allow you to distribute stacks by size).
Andrew Grant Mar 24 '09 at 22:56 2009-03-24 22:56
source share