简体   繁体   English

C ++ STL堆栈:什么时候可以安全地pop()

[英]C++ STL stack: When is it safe to pop()

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". 来自: http : //www.cplusplus.com/reference/stack/stack/pop/ ,“这将调用已删除元素的析构函数”。 Also, from http://www.cplusplus.com/reference/stack/stack/top/ , stack.top() returns by reference. 另外,从http://www.cplusplus.com/reference/stack/stack/top/,stack.top ()通过引用返回。

If S.top() returned by reference and if S.pop() destructed the object, why doesn't obj.display() fail? 如果S.top()引用,如果返回S.pop()破坏的对象,为什么不obj.display()失败?

I know that stack calls the back() and pop_back() methods of the underlying container. 我知道堆栈会调用基础容器的back()pop_back()方法。 By extension, why doesn't that fail? 顺便说一下,那为什么不失败呢?

auto obj = S.top(); copy initializes obj from S.top() . 复制S.top() 初始化 obj 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(); 如果要进行引用,它将是未定义的,例如auto& obj = S.top();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM