zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++里怎么样让类对象删除时自动释放动态分配的内存?

C++内存自动对象 删除 释放 怎么样
2023-09-14 09:10:36 时间

经常有这样的需求,在一个类里一些成员变量需要动态地分配内存,以前是把这个成员声明为指针,然后在构造函数里指定为NULL类型,然后在析构函数里判断这个指针是否分配了内存,如果分配了就进行删除。这种方式需要人工来做,工作量有点大,能否有更加高效的,能否有偷赖的方式呢?这是有的,如下的例子:

#include <memory>
class widget
{
private:
    std::unique_ptr<int> data;
public:
    widget(const int size) { data = std::make_unique<int>(size); }
    void do_something() {}
};

void functionUsingWidget() {
    widget w(1000000);   // lifetime automatically tied to enclosing scope
                // constructs w, including the w.data gadget member
    // ...
    w.do_something();
    // ...
} // automatic destruction and deallocation for w and w.data

在这里自动地分配1000000个int,当w对象不要时,就自动删除了。是利益于使用std::unique_ptr,从这里就可以学习到这个智能指针的使用了,它主要用来私有的数据成员。