Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Object variations

This is a very newbie question, but something completely new to me. In my code, and everywhere I have seen it before, new objects are created as such...

MyClass x = new MyClass(factory);

However, I just saw some example code that looks like this...

MyClass x(factory);

Does that do the same thing?


1 Answers

Not at all.

The first example uses dynamic memory allocation, i.e., you are allocating an instance of MyClass on the heap (as opposed to the stack). You would need to call delete on that pointer manually or you end up with a memory leak. Also, operator new returns a pointer, not the object itself, so your code would not compile. It needs to change to:

MyClass* x = new MyClass(factory);

The second example allocated an instance of MyClass on the stack. This is very useful for short lived objects as they will automatically be cleaned up when the leave the current scope (and it is fast; cleaning up the stack involves nothing more than incrementing or decrementing a pointer).

This is also how you would implement the Resource Acquisition is Initialization pattern, more commonly referred to as RAII. The destructor for your type would clean up any dynamically allocated memory, so when the stack allocated variable goes out of scope any dynamically allocated memory is cleaned up for you without the need for any outside calls to delete.

like image 77
Ed S. Avatar answered Mar 06 '26 06:03

Ed S.



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!