I'm new to C++, I have a class hold some memory, the class looks like:
class MyClass
{
public:
MyClass (int s)
{
if (s <= 0) _size = 1;
else _size = s;
data = new int[_size]; // may throw exception
}
private:
int *data;
int _size;
};
To my knowledge, throw exception in constructor is unsafe, so I put the malloc to a init function.
class MyClass
{
public:
MyClass (int s)
{
if (s <= 0) _size = 1;
else _size = s;
}
void init()
{
data = new int[_size];
}
private:
int *data;
int _size;
};
my problem:
- memory alloc in constructor or init function, which is better
- if I chose init function, how to ensure init function has called before call other member function?
init()
introduces other issues for you so don't do it! – Bezant