考虑:
#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();
更多推荐
发布评论