对列表和删除元素的澄清
如果我有一个 list
并且想要弹出列表中的第一个对象并将其移交给程序的另一部分,使用是否正确(粗略代码)
object* objPtr = queue->first();
queue->pop_first();
return objPtr; // is this a pointer to a valid memory address now?
:?
根据 http://www.cplusplus.com/reference/stl/ 上的文档list/pop_front/ 它调用已删除元素的析构函数,但我很困惑它是否意味着链表的节点对象,或者实际存储的“用户”对象。
编辑:我可能是 front
而不是 first
,我的错。
If I have a list<object*>>* queue
and want to pop the first object in the list and hand it over to another part of the program, is it correct to use (sketchy code):
object* objPtr = queue->first();
queue->pop_first();
return objPtr; // is this a pointer to a valid memory address now?
?
According to the documentation on http://www.cplusplus.com/reference/stl/list/pop_front/ it calls the destructor of the deleted element, but I'm confused as to whether it means the linked list's node object, or the actually stored "user" object.
Edit: I might be front
instead of first
, my bad.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是的,这是一个有效的指针。 List不会释放你分配的内存。列表将破坏其内部而不是用户对象。
Yes, it is a valid pointer. List will not release the memory allocated by you. List will destroy its internal not the user object.
是的,它是有效的:由于您将指针放入列表中,因此只有指针被销毁,而不是对象本身。
Yes it's valid: Since you put pointers into the list, only the pointer gets destroyed, not the object itself.
是的
objPtr
包含指向有效内存的指针。当您将元素插入
std::list
时,list
制作它的副本。在您的情况下,元素是一个地址(指针),因此列表会复制该地址并存储它。optr 现在指向对象,
从
列表
中删除元素(地址/指针),optr
已经指向您的对象。使用完该对象后,不要忘记删除它,否则最终会导致内存泄漏。
例子:
Yes
objPtr
contains pointer to a valid memory.When you insert an element into a
std::list
,list
makes a copy of it. In your case the element is an address (a pointer) so list makes a copy of the address and stores it.optr now points to the object
removes the element (an address/pointer) from the
list
,optr
already points to your object.After you're done with the object don't forget do delete it otherwise you end up with memory leak.
Example:
标准确实说(23.2.2.3/5)调用元素类型的析构函数。但这里这个类型是一个指针,而指针的析构函数什么也不做……
The standard indeed says (23.2.2.3/5) that the destructor of the element's type is called. But this type is a pointer here, and the destructor of a pointer does nothing...
您的代码很好,但最好使用
list<; boost::shared_ptr<对象>; >
。Your code is well but it is better to use
list< boost::shared_ptr<object> >
.当您删除元素时,STL 容器不会破坏堆上分配的用户对象。
如果从列表中删除该 ptr,列表不会自动删除该对象。一旦不再使用该对象,您需要显式调用delete。
When you remove the elements, STL containers will not destroy the user objects allocated on heap.
If you remove the ptr from the list, list will not delete the object automatically. You need to explicitly call delete once the object is no longer being used.