初始化列表中的C++临时变量

C++ temporary variables in initialization list

本文关键字:变量 C++ 列表 初始化      更新时间:2023-10-16

在C++中,有没有任何方法可以在初始化列表中拥有类似临时变量的东西。我想用某个东西的相同实例初始化两个常量成员,而不必传入该东西,删除const要求,使用工厂(即传入它,但让工厂生成它以向API用户隐藏它),或者让temp实际上是成员变量。

即类似的东西

Class Baz{
    const Foo f;
    const Bar b;
    Baz(Paramaters p):temp(p),f(p,temp),b(p,temp){ //temp is an instance of Something
                                                  // But NOT A member of Baz
    // Whatever
    }
}

而不是

Class Baz{
    Foo f;
    Bar b;
    Baz(Paramaters p){
        Something temp(p);
        f = Foo(p,temp)
        b = Bar(p,temp)
    }
}

Class Baz{
    Foo f;
    Bar b;
    Baz(Paramaters p,Something s):f(p,s),b(p,s){
    }
}

在C++11中,您可以使用委托构造函数:

class Baz{
    const Foo f;
    const Bar b;
    Baz(Paramaters p) : Baz(p, temp(p)) { } // Delegates to a private constructor
                                            // that also accepts a Something
private:
    Baz(Paramaters p, Something const& temp): f(p,temp), b(p,temp) {
        // Whatever
    }
};

有几种模式可以实现这一点。

在C++11中使用委托构造函数:

class Baz {
public:
    Baz(Paramaters p) :
        Baz{p, Something{p}}
    {}
private:
    Baz(Paramaters p, Something temp) :
        f{p, temp},
        b{p,temp}
    {}
    const Foo f;
    const Bar b;
};

使用基类:

class BazBase {
public:
    BazBase(Paramaters p, Something temp) :
        f{p, temp},
        b{p,temp}
    {}
protected:
    const Foo f;
    const Bar b;
};
class Baz : private BazBase {
public:
    Baz(Paramaters p) :
        BazBase{p, Something{p}}
    {}
};

使用工厂方法:

class Baz {
public:
    static Baz make(Parameters p)
    {
        return {p, Something{p}};
    }
private:
    Baz(Paramaters p, Something temp) :
        f{p, temp},
        b{p,temp}
    {}
    const Foo f;
    const Bar b;
};