class some_class{
public:
some_class(int);
~some_class();
private:
int *ptr1;
int *ptr2;
int *ptr3;
int *ptr4;
};
In the constructor, I would do this:
some_class::some_class(int some_val)
{
try{
ptr1 = new int(some_val);
}
catch(bad_alloc)
{
std::cout << "Unable to allocate memory." << std::endl;
return; // Skip the rest of the constructor.
}
// Begin the absurdity...
try{
ptr2 = new int(some_val);
}
catch(bad_alloc)
{
delete ptr1; // We can safely assume that ptr1 was allocated by this point.
ptr1 = NULL; // Safe delete...
std::cout << "Unable to allocate memory." << std::endl;
return; // Skip the rest of the constructor.
}
try{
ptr3 = new int(some_val);
}
catch(bad_alloc)
{
delete ptr1; // We can safely assume that ptr1 was allocated by this point.
ptr1 = NULL; // Safe delete...
delete ptr2; // We can safely assume that ptr2 was allocated by this point.
ptr2 = NULL; // Safe delete...
std::cout << "Unable to allocate memory." << std::endl;
return; // Skip the rest of the constructor.
}
try{
ptr4 = new int(some_val);
}
catch(bad_alloc)
{
delete ptr1; // We can safely assume that ptr1 was allocated by this point.
ptr1 = NULL; // Safe delete...
delete ptr2; // We can safely assume that ptr2 was allocated by this point.
ptr2 = NULL; // Safe delete...
delete ptr3; // We can safely assume that ptr3 was allocated by this point.
ptr3 = NULL; // Safe delete...
std::cout << "Unable to allocate memory." << std::endl;
}
}
As you can see, depending on the number of pointers to be allocated, this can approach absurd levels rather quickly. However...
some_class::some_class(int some_val)
{
try{
ptr1 = new int(some_val);
}
catch(bad_alloc)
{
std::cout << "Unable to allocate memory." << std::endl;
return; // Skip the rest of the constructor.
}
// Much more clarity, less absurdity...
try{
ptr2 = new int(some_val);
}
catch(bad_alloc)
{
some_class::~some_class();
std::cout << "Unable to allocate memory." << std::endl;
return; // Skip the rest of the constructor.
}
try{
ptr3 = new int(some_val);
}
catch(bad_alloc)
{
some_class::~some_class();
std::cout << "Unable to allocate memory." << std::endl;
return; // Skip the rest of the constructor.
}
try{
ptr4 = new int(some_val);
}
catch(bad_alloc)
{
some_class::~some_class();
std::cout << "Unable to allocate memory." << std::endl;
}
}
some_class::~some_class()
{
if(ptr1 != NULL)
{
delete ptr1;
ptr1 = NULL;
}
if(ptr2 != NULL)
{
delete ptr2;
ptr2 = NULL;
}
if(ptr3 != NULL)
{
delete ptr3;
ptr3 = NULL;
}
if(ptr4 != NULL)
{
delete ptr4;
ptr4 = NULL;
}
}
This is much more clear and compiles, however, I have heard that calling destructors directly is either a bad thing or frowned upon. Am I doing this correctly in the first place? Is there a better way? Is it OK to call the destructor in this case?
Edited by MarkS, 15 October 2012 - 12:30 PM.






