C ++ STL堆栈:什么时候可以安全地使用pop()(C++ STL stack: When is it safe to pop())

编程入门 行业动态 更新时间:2024-10-17 11:29:29
C ++ STL堆栈:什么时候可以安全地使用pop()(C++ STL stack: When is it safe to pop())

考虑:

#include <iostream> #include <stack> class Abc { int x = 5; public: void display() { std::cout << x << std::endl; } }; int main() { std::stack<Abc> S; S.emplace(); auto obj = S.top(); S.pop(); obj.display(); return 0; }

来自: http : //www.cplusplus.com/reference/stack/stack/pop/ ,“这将调用已移除元素的析构函数”。 另外,从http://www.cplusplus.com/reference/stack/stack/top/,stack.top ()通过引用返回。

如果S.top()通过引用返回,并且如果S.pop()销毁该对象,为什么不obj.display()失败?

我知道栈调用底层容器的back()和pop_back()方法。 通过扩展,为什么没有失败?

Consider:

#include <iostream> #include <stack> class Abc { int x = 5; public: void display() { std::cout << x << std::endl; } }; int main() { std::stack<Abc> S; S.emplace(); auto obj = S.top(); S.pop(); obj.display(); return 0; }

From: http://www.cplusplus.com/reference/stack/stack/pop/, "This calls the removed element's destructor". Also, from http://www.cplusplus.com/reference/stack/stack/top/, stack.top() returns by reference.

If S.top() returned by reference and if S.pop() destructed the object, why doesn't obj.display() fail?

I know that stack calls the back() and pop_back() methods of the underlying container. By extension, why doesn't that fail?

最满意答案

auto obj = S.top(); 复制从S.top() 初始化 obj 。 它是随后移除的元素的副本。

你的代码片段具有明确定义的行为。

如果你需要一个引用,如auto& obj = S.top();

auto obj = S.top(); copy initializes obj from S.top(). It's a copy of the then removed element.

You code snippet has well defined behavior.

It will be undefined if you were to take a reference, like auto& obj = S.top();

更多推荐

本文发布于:2023-08-06 16:05:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1450307.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:什么时候   堆栈   STL   safe   stack

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!