Suppose I have a class A, which uses dynamic memory allocation, like an array or a matrix. During the creation of an object A, through the constructor are passed the parameters which determine how much memory space is being allocated.
class A
{
int * ptr;
int size;
void allocate() noexcept;
void destroy() noexcept;
public:
A(int) noexcept;
~A() noexept;
}
void A::destroy() noexcept
{
if(ptr!=nullptr)
delete [] ptr;
}
A::~A() noexcept
{ destroy();}
void A::allocate() try
{
ptr = new int[n];
}
catch (std::bad_alloc & ex)
{
std::cerr << ex.what();
destroy();
}
A::A(int n) noexcept : size(n) { allocate(); };
Are these kinds of things a good practice, design wise? What would happen to an object that cannot be created in the intended way? Would it remain "alive", like a zombie object, or would it be destroyed?
What to do in the matrix scenario, where the matrix is allocated with the multiple new statements?
Smart pointers, STL and that kind of stuff is not an option here.
READ ME: This class is a demonstrative class, purely made for this kind of issue. It doesn't follow the rule of 0/3/5, because it would be too much code to write just for a question, and it isn't important for this question. There already exists a bunch of questions regarding those issues.