Will std::queue::front
take front element out of the line? And if not how to delete it?
There is a function for getting the element, another for deleting it:
typedef queue<MyClass> MyQueue;
MyQueue q;
q.push(MyClass(42));
// ...
MyClass const& rx = q.front();
rx.print();
MyClass x = q.front(); // Copies the front element to a fresh object
q.pop(); // From this point, rx is a dangling reference
assert(x == MyClass(42));
Rationale: if there were only one pop
function which returns the front element, it wouldn't be possible to get a reference to the front element, since it would have been removed from the queue. If you just want to read a huge element before discarding it, you surely don't want your code to perform a copy.
EDIT: One more fundamental reason is that having two functions means that the user is responsible for making the copy. Assume there is only one single pop
function: what would happen if the copy constructor (inside pop
) throws an exception ? (cf. @Steve Jessop 's comment)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With