C++ temporary variables in initialization list

后端 未结 2 1209
无人共我
无人共我 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:00

    In C++11 you could use delegating constructors:

    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
        }
    };
    
    0 讨论(0)
  • 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;
    };
    
    0 讨论(0)
提交回复
热议问题