Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if 'new' is used to instantiate an object without assigning it to variable?

Want to ask what happens if I write the following and run the program.

new int[5]; // without assigning it to a pointer.

The compilation passed.

But will there be a 5 * sizeof(int) chunk of memory allocated?

What if it is an object?

new some_obj_[5]; // without assigning it to a pointer.

Will the constructor of some_obj_ be invoked?

like image 531
alex wang Avatar asked Dec 16 '22 14:12

alex wang


2 Answers

new int[5];//without assigning it to a pointer.

Yes, there will be a 5*sizeof(int) chunk of memory allocated but inaccessible to you, since you didn't save the pointer. You will have a memory leak.

new some_obj_[5];//without assigning it to a pointer.

Yes, there will be 5*sizeof(some_obj_) chunk of memory allocated but inaccessible to you, since you didn't save the pointer. The default constructor for some_obj_ will be called 5 times. That should be trivial to verify. Depending on how some_obj_ is coded you may have a memory leak.

like image 169
Nik Bougalis Avatar answered Feb 15 '23 23:02

Nik Bougalis


Yes, the array of objects will be dynamically allocated and in the second case the default constructor of some_obj_ will be called. Since you don't store the pointer, you've lost any way to access the objects or delete[] the array, so you have a memory leak.

like image 31
Joseph Mansfield Avatar answered Feb 16 '23 00:02

Joseph Mansfield