Re: std::vector: Surprising order of destruction!
On 2012-05-31 06:20, PiotrN wrote:
I am curious is there any C++ standard rules about destruction of
std::vector elements.
The standard does not specify the order of destruction of the elements.
Neither does it do so for clear(), resize(), and other member functions
that would destroy any element.
For arrays it applies ?reverse order? rule ?
order of destruction is reverse to elements construction ? and it is
in reverse order of indexes.
Well yes, and this is also guaranteed for array-delete expressions.
Nonetheless I think there is a significant difference here: The types
with guaranteed destruction order are fixed-size types, but std::vector
and most other containers have runtime-sizes.
It seems, that, for at least one compiler which I tested, the order of
destruction in std::vector is in natural order of indexes,
Actually I think this is what I also would expect, because it is usually
the most direct way to implement the specification.
which is
very strange to me!
Consider this simple example which failed for std::vector ? whilst
working fine for arrays:
struct T {
T(int i, T* n = 0) : i(i), n(n) { cout<< *this<< endl; }
T(const T& o) : i(o.i), n(o.n) { cout<< *this<< " from "<< o<<
endl; }
~T() { cout<< "~"<< *this<< endl; }
int i;
T* n;
friend ostream& operator<< (ostream& os, const T& t) {
os<< "T("<< t.i;
if (t.n) os<< ","<< *t.n;
return os<< ")";
}
};
1) ARRAY
int main() {
T a[] = { 1, 2, T(3,&a[0]) };
cout<< "main() ended"<< endl;
}
OUTPUT:
T(1)
T(2)
T(3,T(1))
main() ended
~T(3,T(1))
~T(2)
~T(1)
Yes, this is required.
2) VECTOR - surprising order of destruction!
int main() {
vector<T> v;
v.reserve(3);
v.push_back(1);
v.push_back(2);
v.push_back(T(3,&v[0]); */ // that will crash in destruction!!!
}
Yes, presumably.
The question is whether this is really a defect or not. Personally I
have not stumbled across this limitation in real-world projects. But if
you want a normative change, I don't think that specifying the order in
the destructor alone is sufficient. Presumably wording is needed in a
lot of other functions that may destroy elements of the vector. I'm not
convinced that the result is worth the effort behind that. I guess it
will break most if not all existing implementations of std::vector.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]