Reputation: 1949
class test{
int value;
};
class sample{
sample(){
test *var = new test();
}
};
int main(){
sample foo;
//what will happen here if sample constructor fails to allocate its memory?
}
Is it right to use the new
operator inside a C++ constructor?
What will happen here if the sample
constructor fails to allocate its memory?
Upvotes: 1
Views: 701
Reputation: 137800
new
will throw a bad_alloc
exception upon failure.
When a constructor exits by exception, the object never reaches the point of being constructed. Its destructor does not run.
If the exception is thrown within the constructor body, all the object's member variables get destroyed (by destructor calls). If the exception is thrown from the constructor of a member, then the preceding members' destructors run. The point is to undo whatever the constructor has done so far, no more and no less.
There shouldn't be anything smelly about any of this. Do take care that member destructors will always behave properly. This may involve being more fastidious about class invariants. C++ wants to take care of exceptional conditions so you don't need to write a lot of corner cases… but the flip side is that the corner cases still exist, implicit and unspoken.
Upvotes: 2
Reputation: 1
what will happen here if sample constructor fails to allocate a memory?
It will throw a std::bad_alloc
exception and can be sanitized in main()
by catching it:
int main() {
try {
sample foo;
// Work with foo ...
}
catch(const std::bad_alloc& ba) {
std::err << "Not enough memory available. Caught 'bad_alloc' exception: '"
<< ba.what() << "'" << std::endl;
}
}
Upvotes: 2