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?
}
new
sample
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;
}
}