user1762571 user1762571 - 21 days ago 9
C++ Question

Is it right to use new operator inside C++ constructor?

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?

Answer

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;
    }
}
Comments