pythonscripter
pythonscripter

Reputation:

Declaring Dynamic Memory Statements C++

Hi if I am creating something on the stack using new I declare it like:

object *myObject = new object(contr, params);

Is there a way to declare this such as:

object *myObject;
myObject = new object(constr, params);

Is this correct?

Upvotes: 2

Views: 577

Answers (5)

John Dibling
John Dibling

Reputation: 101456

This code:

object *myObject;
myObject = new object(constr, params);

...is legal & correct. But please please initialize myObject to something when you allocate it. Remember 'myObject' is itself not an instance of the 'object', but an instance of a pointer to an 'object'. So when you declare this pointer like this:

object *myObject;

...you are leaving it uninitialized. Instead, do this:

object *myObject = 0;
myObject = new object(constr, params);

...and when you delete it:

delete myObject;
myObject = 0;

People may debate that you should set it to NULL rather than 0, but both are fine as far as the language is concerned and this is mostly a matter of style and what your coworkers are used to.

Upvotes: 0

Steve Fallows
Steve Fallows

Reputation: 6424

As others have said, new will create *myObject on the heap. For completeness I'll point out that the pointer to the object, called myObject (note there is no *) does reside on the stack the way you declared it. Since stack variables go out of scope when you leave a function, you must delete the object before returning, or transfer the pointer to another variable with a longer lifetime. Neglecting to delete a heap object whose pointer is in a stack variable before returning from a function is sort of the canonical memory leak scenario (though far from the only one)

Upvotes: 3

Mr Fooz
Mr Fooz

Reputation: 111866

If you want the object to be on the stack, you need to say

object myObject(contr, params);

Upvotes: 1

JaredPar
JaredPar

Reputation: 754763

Yes that is correct but it won't allocate on the stack. Instead it will allocate on the heap. If you want to allocate on the stack, declare it this way

object myObject(contr,params);

Upvotes: 2

SoapBox
SoapBox

Reputation: 20609

Yes, that is correct. But new does not create things on the stack, it creates them on the heap.

To create object on the stack you would do:

object myObject(constr, params);

There is no other way to create an object on the stack and once it is created on the stack you can't "recreate" it with the same name later in the same function.

Upvotes: 10

Related Questions