Avoid calling constructor of member variable

后端 未结 9 1590
礼貌的吻别
礼貌的吻别 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:05

    I don't see a good way to achieve what you want. This must be a workaround:

    // Header-File
    class A
    {
        public:
        A();
    
        private:
        B m_B;
        C m_C;
        static int prepareC(B& b);
    };
    
    // cpp-File
    A::A()
    : m_B(1)
    , m_C(prepareC(m_B))
    {
    }
    
    int A::prepareC(B& b)
    {
        b.doSomething();
        b.doMore();
        return b.getSomeValue();
    }
    

    Please ensure that m_B.doSomething(), m_B.doMore() and m_B.getSomeValue() don't touch m_C (directly or indirectly).


    As @Tobias correctly mentions, this solution depends on the order of initialization. You need to ensure that the definitions of m_B and m_C are in this order.


    Updated the code according to @Loki's idea.

提交回复
热议问题