vector of pointer to object - how to avoid memory leak?(指向对象的指针向量 - 如何避免内存泄漏?)
问题描述
我们通常如何处理一个元素是指向对象的指针的向量?我的具体问题是下面提供的代码末尾的注释.谢谢.
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];
}
}
推荐答案
是的,您必须这样做才能避免内存泄漏.更好的方法是制作一个共享指针向量(boost、C++TR1、C++0x、)
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, )
std::vector<std::tr1::shared_ptr<A> > l;
或唯一指针向量 (C++0x) 如果对象实际上不是在此容器和其他对象之间共享
or vector of unique pointers (C++0x) if the objects are not actually shared between this container and something else
std::vector<std::unique_ptr<A>> l;
或使用 boost 指针容器
boost::ptr_vector<A> l;
PS:不要忘记 A 的虚拟析构函数,正如@Neil Butterworth 所说!
PS: Don't forget A's virtual destructor, as per @Neil Butterworth!
这篇关于指向对象的指针向量 - 如何避免内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:指向对象的指针向量 - 如何避免内存泄漏?
基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01