I sometimes need a class in C++ which allocates dynamic memory. Since this can fail, I need to detect when the memory cannot be allocated. Usually, I do this as in the example below, ie. I do not allocate memory in the constructor but have a separate method for this, where a bad_alloc
exception can be caught.
Is there any way to allocate memory in the constructor and catch an exception?
try {
my_class my_instance;
}
catch ...
does not work because the scope of my_instance
is limited to the try
block.
Here is a minimal example:
#include <iostream>
class my_class {
private:
char * data;
public:
my_class () {
data = NULL;
}
~my_class () {
delete [] data;
}
void init () {
data = new char [10000000000];
}
void write (int x) {
data[x] = 1;
}
};
int main() {
my_class my_instance;
try {
my_instance.init();
}
catch (std::bad_alloc&) {
std::cout << "Memory overflow.\n";
return 1;
}
my_instance.write(10);
std::cout << "OK.\n";
return 0;
}