【问题标题】:C++ temporary variables in initialization list初始化列表中的 C++ 临时变量
【发布时间】:2013-06-26 20:11:29
【问题描述】:

在 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++ initialization constants


    【解决方案1】:

    在 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,只是避免这个问题。它是一个库,如果必须开始使用 C++11,我想有些人可能会反对集成它
    • @imichaelmiers:我明白了。您是否可以控制SomethingFooBaz 的定义?例如,您能否向Foo 添加一个成员函数,该函数返回构造它的Something 对象? (这样您就可以在 b 的初始化中使用它作为 b(p,f.get_something())
    【解决方案2】:

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

    在 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;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多