Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between new Object() and Object() [duplicate]

In C++ you can instantiate objects using the new keyword or otherwise...

Object o = new Object();

but you can also just do

Object o = Object();

what exactly is the difference between the two, and why would I use one over the other?

like image 973
kamikaze_pilot Avatar asked Mar 16 '26 20:03

kamikaze_pilot


2 Answers

You can't do Object o = new Object(); The new operator returns a pointer to the type. It would have to be Object* o = new Object(); The Object instance will be on the heap.

Object o = Object() will create an Object instance on the stack. My C++ is rusty, but I believe even though this naively looks like an creation followed by an assignment, it will actually be done as just a constructor call.

like image 152
QuantumMechanic Avatar answered Mar 19 '26 12:03

QuantumMechanic


The first type:

Object* o = new Object();

Will create a new object on the heap and assign the address to o. This only invokes the default constructor. You will have to manually release the memory associated with the object when done.

The second type:

Object o = Object();

Will create an object on the stack using the default constructor, then invoke the assignment constructor on o. Most compilers will eliminate the assignment call, but if you have (intended or otherwise) side-effects in the assignment operation, you should take that into account. The regular way to achieve creating a new object without invoking the assignment operation is:

Object o; // Calls default constructor
like image 20
AK. Avatar answered Mar 19 '26 12:03

AK.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!