在静态地图中动态分配对象。删除必要吗?

时间:2016-06-13 20:30:56

标签: c++

考虑以下设想的例子:

class AllocatedClass {
public:
   AllocatedClass() : dummy(0) {}
private:
  int dummy;
};

class AllocatingClass {
public:
     AllocatingClass() : list() {}
     ~AllocatingClass() {
        // CANNOT delete the elements in list here because there may
        // be more than on instance of AllocatingClass sharing the same
        // static list 
     }
     AddNewObject() {
        list.push_back(new AllocatedClass());
     }
private:
     static std::vector<AllocatedClass*> list;

};

在实施文件

std::vector<AllocatedClass*> AllocatingClass::list;

不管一个类的多个实例是否应该共享一个动态分配的对象列表是一个好主意,有没有办法在程序结束时清理这些新的AllocatedClass对象?考虑到我不想在申请结束前删除它们,这些是否永远不会被删除是否重要?

3 个答案:

答案 0 :(得分:2)

如果对象的生命周期是程序执行的生命周期,那么就不需要用代码释放内存。内存将自动释放。

出于性能原因,许多Linux命令行工具不会在代码中释放内存。 (更快地自动释放内存页面,而不是逐个释放每个对象。)

另一种策略是保留一个单独的AllocatedClass实例列表,然后在以后将它们从该列表中释放(切换对象的所有权)。与std::list<AllocatedClass*> to_be_freed一样。

答案 1 :(得分:1)

  

有没有办法在最后清理这些新的AllocatedClass对象   该计划?

一种解决方案是使用std::shared_ptr并自动完成释放。

#include <memory>
#include <vector>
#include <iostream>

class AllocatedClass 
{
    public:
       AllocatedClass(int n = 0) : dummy(n) {}
       ~AllocatedClass() { std::cout << "I am being destroyed" << '\n'; }
    private:
       int dummy;
};

class AllocatingClass 
{
    public:
         AllocatingClass() {}
         void AddNewObject(int num = 0) 
         {  shared_list.push_back(std::make_shared<AllocatedClass>(num)); }
    private:
         static std::vector<std::shared_ptr<AllocatedClass>> shared_list;
};

std::vector<std::shared_ptr<AllocatedClass>> AllocatingClass::shared_list;

AllocatingClass ac;

int main()
{
    ac.AddNewObject();
    ac.AddNewObject(1);
}

Live Example

请注意,会自动为放置在矢量中的对象调用析构函数。

(顺便说一句,命名你的成员变量list并不是一个好主意。)

答案 2 :(得分:-1)

大多数时候(非常接近于所有时间)创建动态分配对象的对象应该有一个程序员定义的析构函数,以便在对象到达其生命周期时释放内存。 AllocatingClass应该有一个析构函数,因为您使用new分配动态内存。

~AllocatingClass() {
    for (int i = 0 ; i < list.size();i++) {
        if(list[i] != NULL) {
            delete list[i];
            list[i] = NULL;
        }
}

这应该提供一种取消分配内存和安全性的方法,这样就不会删除已经删除的指针。