Re: How to make this exception-safe
Triple-DES wrote:
Consider the following code:
#include <vector>
struct C {
explicit C(int) {} // may throw
private:
C(const C&);
C& operator=(const C&);
};
struct V {
V() {
// may leak if push_back or C::C(int) throws
v_.push_back( new C(2) );
v_.push_back( new C(1) );
v_.push_back( new C(3) );
}
Use vector's reserve() function. Alternatively, use a temporary auto_ptr:
auto_ptr<C> p(new C(2));
v_.push_back(p.get());
p.release();
Note that you must not use the returnvalue of p.release(), because then you
first release ownership while the vector is reallocated. That said, this
still won't work, because the destructor of V will not be called when the
constructor throws, but the destructor of vector<> will not delete the
elements it points to. Therefore: try, catch, rethrow.
Uli
--
Sator Laser GmbH
Gesch??ftsf??hrer: Thorsten F??cking, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]