简体   繁体   English

全球范围内的智能指针

[英]Smart pointer in global scope

I have this smart pointer in top of my cpp file (Global variable): 我的cpp文件(全局变量)顶部有这个智能指针:

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? 我知道函数中的智能指针会在函数结束后自动删除并释放内存,但是在多个函数中使用的全局范围智能指针又如何呢?

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. 但是,将智能指针作为全局变量不是一个好主意。

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. 显然,考虑到动态加载的库,存在一些后果。

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 在这里尝试: 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. 该程序已完成,因此无论如何该内存都会被释放到OS。

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()'. 本质上,就好像智能指针的作用域是函数“ main()”的作用域一样。 Here is from cplusplus.com 这是来自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. 销毁对象本身或销毁值或通过赋值操作或显式调用unique_ptr :: reset更改其值后,unique_ptr对象就会自动删除其管理的对象(使用删除器)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM