我是 C++ 新手,我有一个类拥有一些内存,该类看起来像:
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;
};
据我所知,在构造函数中抛出异常是不安全的,所以我把 malloc 放到了一个 init 函数中。
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;
};
我的问题:最佳答案
To my knowledge, throw exception in constructor is unsafe, so I put the malloc to a init function.
不,这不是“不安全”。这是使构造函数失败的方法。您可能正在考虑析构函数中止或其他具有异常安全保证的问题。
“Init”函数为构造函数引入了一种两阶段方法,这增加了复杂性。除非您需要在没有异常(exception)的环境中工作,否则请避免使用它们。在这种情况下,工厂函数是另一种做事的方式。
memory alloc in constructor or init function, which is better
构造函数。见
std::vector
.if I chose init function, how to ensure init function has called before call other member function?
如果没有运行时检查或外部工具,您就无法静态地进行。
您可以在 init 函数上设置一个标志,然后检查每个成员函数。
关于c++ - 在构造函数或 init 函数中分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67615611/