Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ stack variables and heap variables

When you create a new object in C++ that lives on the stack, (the way I've mostly seen it) you do this:

CDPlayer player;

When you create an object on the heap you call new:

CDPlayer* player = new CDPlayer();

But when you do this:

CDPlayer player=CDPlayer();

it creates a stack based object, but whats the difference between that and the top example?

like image 710
Tony The Lion Avatar asked Sep 17 '10 13:09

Tony The Lion


People also ask

What variables are stored in stack and heap in C?

The layout consists of a lot of segments, including: stack : stores local variables. heap : dynamic memory for programmer to allocate. data : stores global variables, separated into initialized and uninitialized.

Are variables on heap or stack?

Stack and a Heap ? Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM . Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it's allocation is dealt with when the program is compiled.

What are stack variables in C?

Stack, where automatic variables are stored, along with information that is saved each time a function is called. Each time a function is called, the address of where to return to and certain information about the caller's environment, such as some of the machine registers, are saved on the stack.


1 Answers

The difference is important with PODs (basically, all built-in types like int, bool, double etc. plus C-like structs and unions built only from other PODs), for which there is a difference between default initialization and value initialization. For PODs, a simple

T obj;

will leave obj uninitialized, while T() default-initializes the object. So

T obj = T();

is a good way to ensure that an object is properly initialized.

This is especially helpful in template code, where T might either a POD or a non-POD type. When you know that T is not a POD type, T obj; suffices.

Addendum: You can also write

T* ptr = new T; // note the missing ()

(and avoid initialization of the allocated object if T is a POD).

like image 138
sbi Avatar answered Sep 24 '22 00:09

sbi