w4j3d
w4j3d

Reputation: 479

simple dynamic allocation question

What is the difference between this:-

width = new int;

And this:-

int width;

i.e. of what use is the dynamic allocation in the first code?

Upvotes: 0

Views: 130

Answers (5)

zwol
zwol

Reputation: 140540

It's very rare that dynamic allocation of one int would be "of use," though I wouldn't say "never."

Dynamic allocation is useful for large, complicated data structures whose lifetime and/or size is not known at compile time, or that are just plain too big to put on the stack.

Upvotes: 0

Srikanth
Srikanth

Reputation: 11994

The first one allocates space for the integer on heap and allocates space to hold the pointer on stack. It also initializes width to 0. Space allocated on heap has to be de-allocated by the programmer (extra burden). This space on heap can be accessed from anywhere as long as pointer to it is available and the memory is not freed.

Second declaration just allocates space on stack and is freed automatically when the variable goes out of scope. The value of width is garbage.

Upvotes: 0

Palmik
Palmik

Reputation: 2665

What you meant is probably:

int* w1 = new int;
int  w2;

The first is allocated on the heap and you have to take care of thememory with operator delete.

The second is on the stack and ceases to exist after it gets out of the scope (so you do not have to take care of the memory yourself).

Upvotes: 2

Nim
Nim

Reputation: 33655

one is allocated on the heap and the other on the stack, one you have to manage and the other is "automatic", one you access via a de-reference the other you don't...

EDIT: with respect to your second question, not much... there are a few cases, but then you'd almost always use a smart pointer, if not, you're playing with fire... :)

Upvotes: 0

Kos
Kos

Reputation: 72241

The former allocates dynamically one int and returns its address in memory (which is written to the variable width and you have to free it later with delete. It exists until then.

The latter declares a local variable of type int which becomes invalid when it leaves the current scope.

Upvotes: 3

Related Questions