指向对象的指针向量 - 如何避免内存泄漏?
我们通常如何处理其元素是指向对象的指针的向量?我的具体问题是下面提供的代码末尾的注释。谢谢。
class A
{
public:
virtual int play() = 0 ;
};
class B : public A
{
public:
int play() {cout << "play in B " << endl;};
};
class C : public A
{
public:
int play() {cout << "play in C " << endl;};
};
int main()
{
vector<A *> l;
l.push_back(new B());
l.push_back(new C());
for(int i = 0 ; i < l.size();i++)
{
l[i]->play();
}
//Do i have to do this to avoid memory leak? It is akward. Any better way to do this?
for(int i = 0 ; i < l.size();i++)
{
delete l[i];
}
}
How do we ususaly deal with a vector whose elements are pointers to object? My specific question is the comment at the end of the code supplied below. Thanks.
class A
{
public:
virtual int play() = 0 ;
};
class B : public A
{
public:
int play() {cout << "play in B " << endl;};
};
class C : public A
{
public:
int play() {cout << "play in C " << endl;};
};
int main()
{
vector<A *> l;
l.push_back(new B());
l.push_back(new C());
for(int i = 0 ; i < l.size();i++)
{
l[i]->play();
}
//Do i have to do this to avoid memory leak? It is akward. Any better way to do this?
for(int i = 0 ; i < l.size();i++)
{
delete l[i];
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,你必须这样做以避免内存泄漏。更好的方法是创建一个共享指针向量(boost、C++TR1、C++0x、)
或唯一指针向量 (C++0x)(如果对象实际上并未在此容器与其他对象之间共享)
,或者使用 boost 指针容器
PS:不要不要忘记 A 的虚拟析构函数,根据@Neil Butterworth!
Yes, you have to do that to avoid memory leak. The better ways to do that are to make a vector of shared pointers (boost, C++TR1, C++0x, )
or vector of unique pointers (C++0x) if the objects are not actually shared between this container and something else
or use boost pointer containers
PS: Don't forget A's virtual destructor, as per @Neil Butterworth!
使用shared_ptr数组,或者类似的智能指针。请注意,您的基类必须有一个虚拟析构函数,此代码才能正常工作。
Use an array of shared_ptr, or similar smart pointer. And note that your base class must have a virtual destructor for this code to work correctly.
最好的方法是使用智能指针(Boost shared_ptr) 避免此类事情。但如果您需要原始指针,我相信这就是实现的方法。
The best way would be to use smart pointers (Boost shared_ptr) to avoid this kind of things. But if you NEED to have raw pointers I believe this is the way to do it.