Possible Duplicate:
STL containers element destruction order
Is there a guarantee the the elements of an std::vector
would be destroyed from last to first?
Possible Duplicate:
STL containers element destruction order
Is there a guarantee the the elements of an std::vector
would be destroyed from last to first?
2003:5.3.5/6 says about
delete[]
:So if your
std::vector
object's allocator usesdelete[]
then, yes, it is bound to destroy elements in reverse order.However, there is no guarantee that your
std::vector
will work this way (and, in fact, it most likely does not), and I can't find any citations specific to the container.Really, I think it's all down to your allocator and 2003:20.1.5 (which lists the requirements placed upon allocators) doesn't appear to say anything about it.
They standard guarantees this for a raw array, but I can't find anything that would guarantee it for containers.
From
[expr.delete]
(new wording for C++0x):std::vector
(and in fact, all containers in the standard library, possibly excludingstd::array
) do not usedelete[]
to destroy the elements (they useallocator_traits<allocator_type>::destroy
on each element individually), so the above guarantee doesn't apply. And I can find no restrictions onstd::vector
in particular or containers in general, about the order of deletion. For some containers, such a guarantee would be very expensive (e.g.std::forward_list
can't iterate the elements in reverse to delete them, andstd::map
doesn't remember the order in which pairs were added).From
[container.requirements.general]
(C++0x wording):No, there are guarantees for arrays, where all elements are constructed is order and destroyed in the reverse order. This is somewhat consistent with how global objects are handled.
Container members, on the other hand, can be constructed and destroyed in any order using for example
insert
anderase
member functions. To be somewhat consistent and destroy the elements in the reverse order of construction, this would require the containers to keep some kind of log over these changes. Obviously this would be expensive!The best bet is that the container destructor calls
clear()
, which is defined aserase(begin(), end())
, but I cannot find any requirements for that either. The standard only says "linear complexity" in table 65.