5
votes

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?

4
A global smart pointer will release the memory at the end of the program. Very much like a non-smart, non-pointer global variable.Bo Persson
It will be destructed when the application exits - see this question for more detailsSteve Lorimer
It's destructor gets called after main() returnsstijn

4 Answers

1
votes

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.

1
votes

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.

0
votes

Since this is a variable with static duration, the memory will be allocated when this code is loaded, usually that will be on start of your application and freed, when the application finishes. If you use it in functions it should generally be allocated, unless it has been reset in another function.

Obviously there are some ramifications considering dynamically loaded libraries.

-1
votes

The smart pointer will be destroyed at the end of the program as all other objects. So when the destructor is called the pointer will be deleted. Her you get an example which is not even close to a real smart pointer, but it gives the idea:

#include <iostream>
using namespace std;

template <typename T>
struct example {
    T* p_;
    example(T* p): p_{p} {
        cout << "example(T* p)\n";
    }
    ~example() {
        cout << "~example()\n";
        delete p_;
    }
};

int main() {
    cout << "start main\n";
    example<int> p{new int};
    cout << "end main\n";
    return 0;
}

Try it out here: https://ideone.com/rOtQY9

Anyway, the use of a global smart pointer eludes me. The program is finished so the memory would have been released to the OS anyway. The nice thing is that whatever resource has been acquired during construction will also be released for sure (e.g. a file could be closed correctly, or a bitstream buffer could be flushed).