Suppose we have a situation where we need FIFO data structure. For example, consume some events in the order they came in.
Additionally, we need to clear the entire queue from time to time.
std::queue
seems like the perfect fit for doing that, but unfortunately it lacks a function for clearing the container.
So at this point, we have 2 alternatives:
std::queue
- we asked the STL lib what we need. Granted, the STL lib will give us more: it will give us an
std::deque
disguised as astd::queue
- we got back only a part from what we need, namely the pop front and push back but without clear
- we will have to "emulate" clear somehow, without the naive way of looping and popping
std::deque
- we asked the STL lib what we need
- we got back what we asked for, but we've got too much: we also got push front and pop back
Overall, we either received too few or too much, never exactly what we really wanted.
Here is the thing that took me by surprise, while I was trying to provide clear functionality for using with std::queue
which is a member var of my object
struct message
{
};
struct consumer
{
std::queue<message> _pending;
void clear_ver_1()
{
auto will_be_deleted_when_out_of_scope = std::move(_pending);
}
void clear_ver_2()
{
std::queue<message> will_be_deleted_when_out_of_scope;
_pending.swap(will_be_deleted_when_out_of_scope);
}
};
I've read the specs and I can not say for sure if clear_ver_1
will leave the _pending
in a valid but unspecified
state or not. See the string example there.
I'm quite surprised that the specs are so vague about this topic. Am I not looking in the right place?
Thank you all!
Update
It seems there is a non-ignorable difference between assigning and clearing. Internally, queue and deque are almost the same (one is using the other one)