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

imi*_*ers 15 c++ initialization const

在C++中,有没有办法在初始化列表中有类似临时变量的东西.我想初始化两个具有相同实例的常量成员,而不必传递该内容,删除const要求,使用Factory(即将其传入但工厂生成它以将其隐藏在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
    }
}
Run Code Online (Sandbox Code Playgroud)

代替

Class Baz{
    Foo f;
    Bar b;
    Baz(Paramaters p){
        Something temp(p);
        f = Foo(p,temp)
        b = Bar(p,temp)
    }
}
Run Code Online (Sandbox Code Playgroud)

要么

Class Baz{
    Foo f;
    Bar b;
    Baz(Paramaters p,Something s):f(p,s),b(p,s){
    }
}
Run Code Online (Sandbox Code Playgroud)

And*_*owl 23

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