矢量::清除:内存问题
Vector::Clear() 将删除向量数组中的元素。
问题是,如果我们在向量列表中传递对象,那么 Clear() 是否会删除对象的内存。
我发布了我的示例:
CData *m_data = new CData();
vector<CData*> m_logdata;
m_logdata.push_back(m_data);
m_logdata.clear();
这段代码会删除 m_data 分配的内存还是简单地删除向量列表中的元素?
问候, 卡蒂克
Vector::Clear() will erase the elements in the vector array.
The issue is that if we pass objects in vector list then Clear() will delete the memory of objects or not.
I post my sample:
CData *m_data = new CData();
vector<CData*> m_logdata;
m_logdata.push_back(m_data);
m_logdata.clear();
will this code delete the memory allocated by m_data or simply remove the element in the vector list?
Regards,
karthik
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有向量,但有向量。
vector.clear() 将破坏向量中的对象。如果这些对象是指针,则不会删除所指向的对象。
在您编辑的帖子上:
这不会删除您的
CData
实例。它只会破坏指针,这是一个空操作。编辑:回应评论。
There's no Vector, there is a vector though.
vector.clear() will destruct the objects in the vector. If these objects are pointers, it will not delete the pointed to objects.
On your edited post:
This will not delete your
CData
instance. It'll simply destruct the pointer which is a no-op.EDIT: In response to comment.
这个问题很模糊......但无论哪种方式,我猜您想知道在调用
clear()
时存储在vector
中的指针是否会自动删除。事实并非如此。无论您在
vector
中存储什么内容,当clear()
发生时,都会调用其析构函数。原始类型(例如指针)的析构函数不执行任何操作。从我的 SGI 实现来看:
要正确删除任何 STL 容器中的项目指针,最简单的方法是创建一个函子并将其应用于每个项目:
The question is quite vague... but either way, I guess that you are wondering if pointers stored in a
vector
would automatically be deleted whenclear()
is called.This is not the case. Whatever you store in a
vector
will have its destructor called whenclear()
occurs. And the destructor of a primitive type (such as a pointer) does.. nothing.From my SGI implementation:
To properly delete items pointers in any STL container, the easiest way is to create a functor and apply it on every item: