C++ temporary variables in initialization list

后端 未结 2 1208
无人共我
无人共我 2020-12-29 07:28

In C++, is there any way to have something like a temporary variable in an initialization list. I want to initialize two constant members with the same instance of something

2条回答
  •  囚心锁ツ
    2020-12-29 08:12

    There's a couple of patterns to achieve this.

    In C++11 use delegating constructors:

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

    Use a base class:

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

    Use a factory method:

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

提交回复
热议问题