在构造函数或 init 函数中分配内存?

dan*_*ipi 4 c++ oop constructor initialization raii

我是 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;
};
Run Code Online (Sandbox Code Playgroud)

据我所知,在构造函数中抛出异常是不安全的,所以我把 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;
};
Run Code Online (Sandbox Code Playgroud)

我的问题:

  1. 构造函数或init函数中的内存分配,哪个更好
  2. 如果我选择了 init 函数,如何确保在调用其他成员函数之前已经调用了 init 函数?

Aco*_*orn 5

据我所知,在构造函数中抛出异常是不安全的,所以我把 malloc 放到了一个 init 函数中。

不,这不是“不安全”。这是使构造函数失败的方法。您可能正在考虑析构函数中止或其他具有异常安全保证的问题。

“Init”函数为构造函数引入了一种两阶段方法,这增加了复杂性。除非您需要在没有例外的环境中工作,否则请避免使用它们。在这种情况下,工厂函数是另一种做事的方式。

构造函数或init函数中的内存分配,哪个更好

构造函数。见std::vector

如果我选择了 init 函数,如何确保在调用其他成员函数之前已经调用了 init 函数?

如果没有运行时检查或外部工具,您就无法静态地进行。

您可以在 init 函数上设置一个标志,然后检查每个成员函数。