删除向量类成员 [英] Delete vector class member
问题描述
我有一个成员为A的类A,该成员是另一个B的对象指针的向量
I have a class A with a member which is a vector of object pointers of another class B
class A
{
std::vector<B*> m_member_A
通过使用new
运算符创建B的对象来填充
m_member_A
m_member_A
is populated by creating objects of B by using new
operator
B* b1 = new B;
m_member_A.push_back(b1);
在A的析构函数中,以下是否正确以释放所有内容?
In A's destructor, is the following correct to free up everything?
A::~A()
{
for(int i = 0; i < m_member_A.size(); ++i)
{
delete m_member_A[i];
}
m_member_A.clear();
}
推荐答案
It's correct, as long as you also have a correct copy constructor and copy-assignment operator per the Rule of Three. Note that the clear()
is redundant, since the vector's destructor will release its memory.
为什么要弄乱指针和new
?为什么不遵循零规则,并使用vector<B>
或vector<unique_ptr<B>>
(如果您需要多态性的指针)?然后,您完全不必担心析构函数,复制构造函数或复制分配运算符;并且您将获得移动语义作为奖励.
By why are you messing around with pointers and new
? Why not follow the Rule of Zero, and use vector<B>
, or vector<unique_ptr<B>>
if you need pointers for polymorphism? Then you shouldn't need to worry about a destructor, copy constructor or copy-assignment operator at all; and you'll get move semantics as a bonus.
这篇关于删除向量类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!