I am confused by the reference to the top element of a stack.
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> s;
s.push(1);
int x = s.top();
int& y = s.top();
const int& z = s.top();
cout << x << '\t' << y << '\t' << z << endl;
s.pop();
s.push(2);
cout << x << '\t' << y << '\t' << z << endl;
}
/* Output:
1 1 1
1 2 2
*/
I thought the reference to the top element should NOT be changed, but after a new element is pushed to the stack, the value that reference refers to is changed.
This is weird to me, because if the type is NOT int
for the stack, say it's type of MyClass
(very big data), is there a way to safely refer to the old top element? (Because I don't want to make an expensive copy operation).
I guess this behavior might be implementation-dependent, sign!