The const reference returned by
const int & m = queue.top();
cout << m << endl; // 3
cout << m << endl; // 2
cout << m << endl; // 1
auto & m = queue.top();
3 2 1
auto m = queue.top();
3 3 3
If get top value by
auto & m = queue.top();, then output is also
3 2 1.
Despite it is calling undefined behavior to use
m after the 1st
pop() call, it is likely that the next value is moved to that dangling reference (address). That is because the default underlying type of
std::vector, which guarantees a contiguous array of elements.
But as mentioned that behavior is undefined, and there are no guarantees to reproduce that result with a different compiler.
While if get top value by
auto m = queue.top();, then output is
3 3 3.
The value from
top is stored into
m once, and never changed afterwards.