j4nu5 j4nu5 - 28 days ago 7
C++ Question

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".
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?

Answer

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();

Comments