The difference between Object var and Object * var = new Object ()

If I have a class called Object, what's the difference between instantiating just like this:

Object var; 

and

 Object* var = new Object(); 

?

+4
source share
5 answers

Here you create var on the stack:

 Object var; 

So, in the above example, var is the actual object.


Here you create var on the heap (also called dynamic allocation):

 Object* var = new Object() 

When creating an object on the heap, you must call delete on it when you finish using it. In addition, var is actually a pointer that stores the memory address of an object of type Object . An actual object exists on the memory address.


For more information: See my answer here, where and where are the stack and heap .

+17
source

It:

 Object var(); 

It is a function declaration. It declares a function that takes no arguments and returns an Object . What did you mean:

 Object var; 

which, as others have noted, creates a variable with automatic storage duration (aka, on the stack).

+11
source
 Object var(); 

Declaring a function that returns an Object . To create an automatic object (i.e., on the stack):

 Object var; // You shouldn't write the parenthesis. 

While:

 Object* var = new Object(); 

It is a dynamically allocated Object .

+5
source
 Object var; 

creates an object that is valid until the end of the current region, usually up to '}'

 Object* varp = new Object(); 

creates a pointer to a newly created object. The pointer (varp) is valid until en d of the scope, but the object itself exists until deletion is called on the pointer.

You should always prefer the first version if there is no reason to do the second. The second version takes up more memory (you need space for the pointer, as well as the object), takes more time (the system needs to allocate memory on the heap), and you need to call delete to free the memory when you are done with it.

+3
source
 Object var(); 

Allocates an object on the stack, so you do not need to free it

 Object* var = new Object(); 

allocates an object on the heap

+1
source

Source: https://habr.com/ru/post/1312975/


All Articles