Re: Exception in Constructor
On 2012-09-17 02:25, MiB wrote:
If there is a chance code in a constructor with dynamic allocation
generates an exception, I recommend to catch any inside the
constructor itself individually and releasing all such resources
before re-throwing the exception.
E.g:
class A {
private:
char* cstr1;
char* cstr2;
char* cstr3;
public:
A() {
cstr1 = new char[1000]; // no need to catch here,
// no cleanup on fail
try {
cstr2 = new char[1000000]; // may fail
}
catch ( std::bad_alloc ) {
delete cstr1;
throw;
}
try {
cstr3 = new char[1000000]; // may fail
}
catch ( std::bad_alloc ) {
delete cstr1;
delete cstr2;
throw;
}
}
};
I prefer this over nested try..catch even if it means (minor) code
duplication. The point is to leave behind an object that only needs
to have its own memory released on exception.
I would rather not follow this recommendation. First of all, the code
invokes undefined behaviour because it releases memory that was
allocated via new[] with non-array delete. Second, there is no need to
use try and catch at all. The trick is to have resources managed by
objects, also known as RAII.
class A
{
private:
std::vector<char> cstr1;
std::vector<char> cstr2;
std::vector<char> cstr3;
public:
A()
: cstr1(1000),
cstr2(1000000),
cstr3(1000000)
{
}
};
achieves the desired effect a lot cleaner and is perfectly safe.
--
Gerhard Menzl
Non-spammers may respond to my email address, which is composed of my
full name, separated by a dot, followed by at, followed by "sabre",
followed by a dot, followed by "com".
X-No-Acknoledgement: yes
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]