使用中间结果初始化多个属性

Using an intermediate result to initialise several attributes

本文关键字:属性 初始化 结果 中间      更新时间:2023-10-16

我有一个类,其构造函数大致是这样做的:

class B;
class C;
class D;  
class A{
private:
  B b;
  C c;
public:
  A(istream& input){
    D d(input) // Build a D based on input
    b = B(d);  // Use that D to build b
    c = C(d);  // and c
  }
}

应该工作良好,只要BC有默认构造函数。

我的问题是B没有,所以我需要在初始化列表中初始化b。但这是一个问题,因为我需要在计算bc之前构建d

一种方法是:

A(istream& input):b(D(input)),c(D(input)){}

但是建造一个D(非常)昂贵(*)

有什么干净的方法可以解决这个问题?


(*)另一个问题是,如果bc需要从同一个实例构建(如D的构造函数是随机的或其他)。但这不是我的情况。

在c++ 11中可以使用委托构造函数:

class B;
class C;
class D;
class A
{
private:
    B b;
    C c;
public:
    explicit A(istream& input)
        :
        A(D(input))
    {
    }
    // If you wish, you could make this protected or private
    explicit A(D const& d)
        :
        b(d),
        c(d)
    {
    }
};