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

标签 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;
};
据我所知,在构造函数中抛出异常是不安全的,所以我把 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;
};
我的问题:
  • 构造函数或init函数中的内存分配,哪个更好
  • 如果我选择了 init 函数,如何确保在调用其他成员函数之前已经调用了 init 函数?
  • 最佳答案

    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/

    相关文章:

    swift - 如何在类层次结构中应用 Swift 泛型/协议(protocol)?

    c++ - `std::filesystem::path::operator/(/*args*/)` 没有按预期工作

    c# - ListViewItem 构造

    c++ - 模板类相互使用会产生歧义错误

    c++ - 如何在不使用任何第三方库的情况下在 C++ 中反序列化 json 字符串

    java - Java中的重构: Duplicated attributes

    ruby - 在实例化时将类转换为子类

    c++ - C++ 中谓词的逻辑否定

    c++ - std::bind 导致析构函数出现段错误

    c++ - 为什么 atomic_flag 默认构造函数未指定状态?