-2

Documentation states std::priority_queue::top returns a constant reference to the top element in the priority_queue, but when printing the top element, the unary dereference operator is not used.

// priority_queue::top
#include <iostream>       // std::cout
#include <queue>          // std::priority_queue

int main ()
{
  std::priority_queue<int> mypq;

  mypq.push(10);
  mypq.push(20);
  mypq.push(15);

  std::cout << "mypq.top() is now " << mypq.top() << '\n';

  return 0;
}

Is top() being implicitly dereferenced or is the returned value a copy?

Kevin
  • 97
  • 9

2 Answers2

1

You don't need to dereference a reference. You only need to dereference a pointer, not a reference.

Andrei Chernikov
  • 360
  • 1
  • 2
  • 12
1

Is top() being implicitly dereferenced or is the returned value a copy?

No there's no value copy, unless you make one. As from the reference documentation std::priority_queue::top() returns a const &T:

const_reference top() const; Returns reference to the top element in the priority queue. This element will be removed on a call to pop(). If default comparison function is used, the returned element is also the greatest among the elements in the queue.

If you use

 int x = mypq.top();

a copy is made. If you use

 const int& x = mypq.top();

you'll have a direct (const) reference.

but when printing the top element, the unary dereference operator is not used.

Supposed you meant one of the dereferncing operations, dereferencing references isn't needed at all, think of aliases to the original value instead. You can overload these operators though for T, but that doesn't affect std::priority_queue::top().

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190