Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will std::queue front take front element out of the line?

Tags:

c++

std

queue

Will std::queue::front take front element out of the line? And if not how to delete it?

like image 850
Rella Avatar asked Dec 13 '22 18:12

Rella


1 Answers

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)

like image 50
Alexandre C. Avatar answered Dec 30 '22 12:12

Alexandre C.