使用已删除的默认构造函数初始化成员

Initialize members with deleted default constructor

在 C++ 中,如果我想要一个没有默认构造函数的 class 成员,我需要像这样显式初始化它:

class a
{
   a(int)
   {
   }
};

class b
{
   a x;

   b() : x(3)
   {
   }
};

但是,有时 x 等的初始化并没有这么简单。它可以是一个非常非常复杂的公式,也可以是一个完整的算法函数,需要计算 fors 和 ifs。我一般是这样解决的:

class b
{
   a * x;
   b()
   {
      // Do some very complicated computations
      this->x = new a(result_of_complicated_computations);
   }
};

然而,这迫使我在销毁时删除指针,它的性能稍差,并且使我的代码不知何故不整洁和丑陋。我真的很惊讶,没有办法在 class 的构造函数中为成员的构造函数计算参数,而不必使用这种技巧。

是否有更优雅的解决方案?

使用辅助函数:

class b
{
    a x;
    b() : x(complicated_computation()) { }
private:
    static int complicated_computation() {
        return result_of_complicated_computations;
    }
};

并且默认构造函数没有被删除,但未声明。

在函数中进行计算:

static a complicated_computations();
b() : x(complicated_computations()) {}

我不明白。如果你有:

class A
{
private:
    //a lot of members

public:
    A(/* complex object used for construction */)
    : //initialize members
    { }
}

你可以简单地做:

class B
{
private:
    A a;

public:
    B()
    : a(call_to_function_that_generates_this_complex_data())
    { }
};

您甚至可以在构造过程中使用您的成员函数。但请注意:

§ 12.6.2.13:

Member functions (including virtual member functions, 10.3) can be called for an object under construction.(...) However, if these operations are performed in a ctor-initializer (or in a function called directly or indirectly from a ctor-initializer) before all the mem-initializers for base classes have completed, the result of the operation is undefined.