这是 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/