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

Will std::queue::front output front element from string? And if you do not delete it?

+4
source share
3 answers

There is a function to get an element, another to remove 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 was only one pop function that returns the front element, it would be impossible to get a reference to the front element, since it would be removed from the queue. If you just want to read a huge element before discarding it, you certainly do not want your code to execute a copy.

EDIT: Another fundamental reason is that having two functions means that the user is responsible for making the copy. Suppose there is only one pop function: what happens if the copy constructor (inside pop ) throws an exception? (see comment by @Steve Jessop)

+7
source

No, it just returns a link to the front element. If you need to take out an element, use pop() . See std :: queue for more details.

+2
source

Front-mode type definitions for a queue.

 value_type& queue::front () const value_type& queue::front () const 

Both forms return the next element of the queue. The caller must verify that the queue contains an element (size ()> 0); otherwise, the behavior is undefined. The first form for mutable queues returns a link. This way you can change the next item while it is in the queue. It is up to you to decide if this is a good style.

Use pop to remove it. It removes the next item from the queue. The next element is the element that was inserted first (before all other elements in the queue). This function has no return value. To process the next element, you must first call front ().

+2
source

All Articles