Re: std::vector: Surprising order of destruction!
In article <jqr8d9$o6e$1@usenet.stanford.edu>,
Seungbeom Kim <musiphil@bawi.org> wrote:
On 2012-06-07 11:57, Nevin ":-]" Liber wrote:
In article <jqp1tv$ebq$1@usenet.stanford.edu>,
Seungbeom Kim <musiphil@bawi.org> wrote:
A user sensible enough could start something with an array, and
then later decide to switch to a vector. If a complex program
crashes just after switching from an array to a vector, the user
will have to spend a good amount of time debugging it in
frustration.
Being dependent on order of destruction within a container is rare.
That is probably so, though others may disagree.
Then, as I paid attention to what may happen when switching from
arrays to vectors, I wonder why arrays have a specified order of
destruction in the first place, and why even temporaries do.
On the other hand, I also wonder if implementations really need the
freedom of the destruction order.
If you really need it, you can always make your own destructor
enforce it.
You mean, by writing your own container class with the destructor
enforcing the destruction order of its elements?
Nothing so drastic. For instance, you can have a wrapper that forces
the behavior, as in:
template<typename C>
struct ForceDestructionOrder
{
explicit ForceDestructionOrder(C& c) : _c(c) {}
~ForceDestructionOrder()
{ while (!_c.empty() { erase(--_c.end()); } }
private:
C& _c;
};
And usage:
class Foo
{
// ...
std::vector<Bar> _vb;
ForceDestructionOrder<decltype(_vb)> _d;
// ...
};
--
Nevin ":-)" Liber <mailto:nevin@eviloverlord.com> 773 961-1620
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]