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:
To my knowledge, throw exception in constructor is unsafe, so I put the malloc to a init function.
No, it is not "unsafe". It's the way to fail a constructor. You may be thinking about destructors aborting or other issues with exception safety guarantees.
"Init" functions introduce a two phase approach to constructors that increases complexity. Unless you need to work in an environment without exceptions, avoid them. Factory functions are another way to do things in that case.
memory alloc in constructor or init function, which is better
Constructor. See std::vector
.
if I chose init function, how to ensure init function has called before call other member function?
Statically you cannot without a run time check or external tools.
You can set a flag on your init function and then check in every member function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With