Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smart pointer in global scope

I have this smart pointer in top of my cpp file (Global variable):

std::unique_ptr<DATA_READ> smartPT(new DATA_READ);

What happens if smart pointer declares in global scope? I know smart pointer in a function automatically deletes and release memory after the function ends but How about Global Scope Smart Pointer which used in multiple functions?

like image 905
Ali Sepehri-Amin Avatar asked Nov 08 '22 15:11

Ali Sepehri-Amin


2 Answers

It will release the allocated memory during the termination of the program. However, it is not a good idea to have smart pointer as global variable.

like image 92
Naseef Chowdhury Avatar answered Nov 14 '22 21:11

Naseef Chowdhury


The memory will remain allocated throughout the life of the program, unless specific action is taken to free the memory. Essentially it will be just as if the scope for the smart pointer is the scope of the function 'main()'. Here is from cplusplus.com

unique_ptr objects automatically delete the object they manage (using a deleter) as soon as they themselves are destroyed, or as soon as their value changes either by an assignment operation or by an explicit call to unique_ptr::reset.

like image 29
MJ_Wesson Avatar answered Nov 14 '22 22:11

MJ_Wesson