Avoid calling constructor of member variable

后端 未结 9 1553
礼貌的吻别
礼貌的吻别 2021-02-19 13:14

I have the following C++-class:

// Header-File
class A
{
    public:
    A();

    private:
    B m_B;
    C m_C;
};

// cpp-File
A::A()
: m_B(1)
{
    m_B.doSom         


        
9条回答
  •  野的像风
    2021-02-19 14:16

    You can't.

    All member variables are full constructed when the construcotr code block is entered. This means there constructors must be called.

    But you can work around this restriction.

    // Header-File
    class A
    {
        struct Initer
        {
             Initer(B& b)
                 : m_b(b)
             {
                 m_b.doSomething();
                 m_b.doMore();
             }
             operator int()  // assuming getSomeValue() returns int.
             {
                 return m_b.getSomeValue();
             }
             B& m_b;
        };
        public:
        A();
    
        private:   // order important.
        B m_B;
        C m_C;
    };
    
    
    // cpp-File
    A::A()
    : m_B(1)
    , m_C(Initer(m_B))
    {
    }
    

提交回复
热议问题