Difference between Object var and Object* var = new Object()

后端 未结 5 1006
醉酒成梦
醉酒成梦 2021-01-20 00:24

If I have a class named Object, what\'s the difference between creating an instance just like that:

Object var;

and:

Object         


        
相关标签:
5条回答
  • 2021-01-20 00:47
    Object var;
    

    creates an Object that is valid until the end of the current scope, generally until the '}'

    Object* varp = new Object();
    

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

    You should always prefer the first version, unless there is a reason to do the second. The second version takes 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 make sure to call delete to free the memory when you are done with it.

    0 讨论(0)
  • 2021-01-20 00:52

    Here you are creating var on the stack:

    Object var;
    

    So in the above, var is the actual object.


    Here you are creating 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're done using it. Also var is actually a pointer which holds the memory address of an object of type Object. At the memory address exists the actual object.


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

    0 讨论(0)
  • 2021-01-20 00:53
    Object var();
    

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

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

    While:

    Object* var = new Object();
    

    Is a dynamically allocated Object.

    0 讨论(0)
  • 2021-01-20 01:05
    Object var();
    

    Allocates object on the stack, so you don't have to deallocate it

    Object* var = new Object();
    

    allocates object on the heap

    0 讨论(0)
  • 2021-01-20 01:07

    This:

    Object var();
    

    Is a function declaration. It declares a function that takes no arguments and returns an Object. What you meant was:

    Object var;
    

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

    0 讨论(0)
提交回复
热议问题