stanleyerror stanleyerror - 21 days ago 5
C++ Question

Why does top()'s return value change after calling pop()?

The const reference returned by

priority_queue
's
top()
changes after calling
pop()
(visual studio 2015)

priority_queue<int> queue;
queue.push(1);
queue.push(2);
queue.push(3);

const int & m = queue.top();
cout << m << endl; // 3
queue.pop();
cout << m << endl; // 2
queue.pop();
cout << m << endl; // 1


If get top value by
auto & m = queue.top();
, then output is also
3 2 1
.

While if get top value by
auto m = queue.top();
, then output is
3 3 3
.

What's mechanism behind this ?

Answer

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::priority_queue is 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.

Comments