0

I have a very basic doute concerning dynamic allocation. Studying the tree following possible syntaxes I have been said that they all are dynamic allocations.

First:

int* px(nullptr); 
px = new int;
*px =20;

Then a more concise one:

int* px(nullptr);
px = new int(20);

Or even:

int*px(new int(20));

Then in a second moment in the same explanation I have been told that the third case is actually a static allocation. Than I got confused.

Is that true? Could someone explain me why please?

Many thanks.

eightShirt
  • 1,457
  • 2
  • 15
  • 29
Paul
  • 123
  • 1
  • 9

2 Answers2

2

What you have in all examples is a combination of static and dynamic allocation, and 2 variables that reside in automatic and dynamic memory respectively.

Pedantically, the pointer px is an automatic variable, and what it points to (*px) is a dynamically-allocated variable.

px is destroyed when it goes out of scope automatically, *px must be cleared explicitly (via a delete px;)

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • Thanks for you answer. Could you please specify which example you are talking about through your text? – Paul Jan 20 '15 at 15:38
  • @Paul all of them. All have a statically-allocated `px` variable of type `int*` and a dynamically-allocated variable (the one pointed to by `px`, or `*px`) of type `int`. – Luchian Grigore Jan 20 '15 at 15:48
  • Perhaps you could start this answer by saying that "all three pieces of code do pretty much exactly the same thing". – Aaron McDaid Jan 20 '15 at 16:26
2

Your first example:

int* px(nullptr);
px = new int;
*px =20;

The first line creates a stack allocated pointer and assigns it the value "nullptr". The second line creates an integer allocated on the heap and assigns px the pointer to that integer. The last line dereferences px and assigns 20 to the heap value.

In your second example:

int* px(nullptr);
px = new int(20);

The second line creates an int allocated on the heap with a value of 20 and assigns it's pointer to px.

In your last example:

int*px(new int(20));

You're creating a heap allocated integer with value 20 and its pointer is passed back as an argument to initialize the integer pointer px. It's the same as:

int* px = new int(20);

So to answer your question, only the lines that contain "new" are dynamic memory allocation.

new = heap allocated, otherwise it's stack allocated, unless you're calling a function/operator that uses new or malloc under the hood.

Michael B.
  • 331
  • 1
  • 5