C++ STL 堆栈 : When is it safe to pop()

标签 c++ c++11 stl

考虑:

#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() 方法。推而广之,为什么没有失败?

最佳答案

auto obj = S.top(); S.top() 复制初始化 obj。它是当时删除的元素的拷贝。

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

如果你要引用,它将是未定义的,比如 auto& obj = S.top();

关于C++ STL 堆栈 : When is it safe to pop(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40446712/

相关文章:

c++ - 返回类型中 && 和 no ref 的区别

c++ - 将两个 vector 对转换为相应元素的映射

C++ STL : Why do STL data structures not provide a function for measuring the memory consumption?

c++ - 如何在 isaplha 中将 *argv[] 变成一个字符串

c++ - 将 vector 模拟为二维数组

c++ - qt 应用程序和 std::shared_ptr

c++ - Erase-remove 习语 : what happens when remove return past-the-end-iterator?

c++ - 用于测试的 IAT Hook

c++ - 将 time_t 转换为字符串

c++ - 查找范围 [a, b] 中不在给定 std::set S 中的所有数字