Is there any guarantee regarding the destruction order of std::stack elements?
I have a class that manages the lifetime of a set of services. Since there may be service interdependencies, the order of construction and destruction is important -- the services should be destroyed in the reverse order of their creation.
I thought I would use a std::stack<std::unique_ptr<Service>>
for this purpose. Knowing that a stack is a container adapter, and guessing that this might affect its destruction semantics, I searched, but I couldn't find any documentation (page 800) that guaranteed the order of destruction for the elements of a std::stack.
In the end, I wrote a little test:
struct Squealer {
Squealer() {
static int instance_count = 0;
this->instance = ++instance_count;
}
~Squealer() {
std::cout << "Destroying instance " << instance << std::endl;
}
int instance;
};
int main(int argc, char *[] argv) {
{
std::stack<Squealer> squealers;
squealers.emplace();
squealers.emplace();
squealers.emplace();
}
std::cout << "...done" << std::endl;
}
The result was as expected:
Destroying instance 3
Destroying instance 2
Destroying instance 1
...done
Should I be relying on this behavior? Is the naive destruction order guaranteed for std::stack, or should I take the (admittedly easy) step of popping it until it is clear?