myVector.erase(myObject) 是否对 myObject 调用删除?
类似于这个问题但使用对象而不是指针。
如果我有以下代码,
Foo f;
vector<Foo> vect;
vect.push_back(f);
vect.erase(vect.begin());
我的对象去了哪里?是否调用了删除?如果其他人持有指向它的指针怎么办?这是内存泄漏吗?
Similar to this question but with objects instead of pointers.
If I have the following code
Foo f;
vector<Foo> vect;
vect.push_back(f);
vect.erase(vect.begin());
Where does my object go? Is delete called on it? What if someone else holds a pointer to it? Is this a memory leak?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
push_back
在向量中存储f
的副本,而erase
则销毁它。f
本身不受此影响。当您
擦除
向量中的元素时,所有指向该元素的指针、引用和迭代器都会失效。在擦除后使用它们访问元素会产生未定义的行为。push_back
stores a copy off
in the vector, anderase
destroys it.f
itself is not affected by that.All pointers, references and iterators to an element in a vector are invalidated when you
erase
it. Using them to access the element aftererase
yields undefined behavior.在您的情况下,
vector
保存f
的副本,而不是指针。在擦除时,它只会销毁该副本。In your case
vector
holds a copy off
, not a pointer. Onerase
it will just destroy that copy.来自 cplusplus.com
在这种情况下,您仍然拥有对象 f,因为您在将其复制(通过推回)到向量之前声明了它。
当您从向量中删除时,将在复制的对象上调用析构函数,并且向量的迭代器将被破坏。
From cplusplus.com
In this case, you still have your object f, because you declared it before copying it (via pushback) into the vector.
When you erase from the vector the destructor is called on the copied object and the vector's iterator are broken.
是的,擦除调用向量中对象的析构函数。
当对象插入向量时,它的复制构造函数被调用,并且它的副本被放入向量中,所以如果你有一个指向
f
的指针(并且没有的副本) f
为向量创建),您无需担心从向量中删除对象的后果。Yes, erase calls the destructor for the object(s) in the vector.
When the object is inserted into the vector, it's copy constructor is called and a copy of it is placed into the vector, so if you have a pointer pointing at
f
(and no the copy off
created for the vector), you don't need to worry about the consequences of deleting objects from the vector.当推回一个元素时,会创建一个副本。
擦除后,副本被破坏,但f仍然有效。
如果您在复制的元素上有一个指针,它将成为悬空引用,这意味着您的指针指向的内容无效。
如果你在复制的元素上使用迭代器,它也会变得无效
When pushing back an element, a copy is made.
After erasing, the copy is destroyed, but f is still valid.
If you have a pointer on the element copied, it will become a dangling reference, meaning that the content pointed by your pointer is invalid.
If you are using an iterator on the copied element, it will also become invalid