c++ - 删除 vector 中的元素(对象)(未被指针引用),内存处理

标签 c++

这是 this question 的扩展.我在网上搜索过,但找不到满意的答案。

我有一个 class A,它定义了一个包含多个 class Region 实例的 vector 。这些 Region 实例的内存处理需要由 Class A

管理

我的问题是:

1.在下面的代码片段中,我是否需要在类A的desctuctor中显式删除这些实例?

2. 我应该将实例创建为 new Region(i) 吗?它是否比第一个选项(不使用 new)更好?A 类是一个相当大的对象。我应该如何确定是否使用新的?

3. 如果 #2 的答案是肯定的,我应该如何在析构函数中删除这些实例? delete Region(i)(在 for 循环中)或 delete [] reg??我猜以前的方法是正确的方法,但想确认一下。

4. 除了“Region instances are not deleted”之外,您是否看到任何明显的内存泄漏...尤其是在 A 中构造 Region 对象时构造函数?

class Region{
   public:
      Region(int num);
      int number;
      std::vector <elemt*> elements;   
      int info;
}

class A{
public:
    std::vector<Region> reg;
    const int numOfRegions = 100;
}

A::A(){
    int i;
    for ( i=0; i<numOfRegions; i++){
        reg.push_back(Region(i));
      } 
}

A::~A(){
  // How should the elements within vector Region be deleted??
  // Should I use "new" to allocate memory to instances of Region()
}

更新: 非常感谢所有回答的人!

最佳答案

In the following code snippet, do I need to explicitly delete these instances in the desctuctor of class A?

不 - 它们会自动为您删除 - 如果您不使用 new 创建它,则不会删除它。

Should I create instances as new Region(i) ? Is it better over the first option (not using new) Class A is quite a large object. How should I determine whether to use new or not?

A 的大小不是问题。这个问题没有明确的答案,但一般规则是,如果您不必使用 new 动态创建对象,则不要这样做。

If Answer to #2 is yes, how should I delete these instances in the destructor ? delete Region(i) (in a for loop) or delete [] reg?? I am guessing former way is the correct way, but want to confirm.

如果您使用 new 创建它们,您将在 for 循环中删除它们:

 delete reg[i];

reg 当然必须是指针 vector 。更好的选择是使用智能指针 vector 。

Other than "Region instances are not deleted" , do you see any obvious memory leak.. especially in the construction of Region object in A's constructor?

它们已被删除 - 只是不是由您删除的。这称为 RAII,是非常非常好的 C++ 实践 - 您应该尽可能使用 RAII。

关于c++ - 删除 vector 中的元素(对象)(未被指针引用),内存处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2236445/

相关文章:

c++ - 在不使用 if 的情况下插入/更新 std::unordered_map 元素的最快方法是什么?

c++ - C++构造函数如何初始化其类的对象?

c++ - 在这种情况下如何使用动态多态性?

c++ - CLR中 native 堆的内存管理

c++ - 模板函数特化说明

c++ - (c/c++) 字符串文字的拷贝是否在 TEXT 部分共享内存?

c++ - 对于不同的点 OpenGL 查看相同的颜色

c++ - 适配器模式 : support underlying data that can be const or non-const, 优雅

c++通用编译时for循环

c++ - DirectX SDK 与 Windows SDK : which one to use?