Avoid calling constructor of member variable

后端 未结 9 1547
礼貌的吻别
礼貌的吻别 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 13:59

    If you don't want to allocate it dynamically using new for code clutter/exception safety reasons, you can use a std::unique_ptr or std::auto_ptr to solve this problem.

    A solution that avoids new is to edit C to have a two-step initialization process. The constructor would then construct a "zombie" object, and you'd have to call an Initialize method on that m_C instance to finish your initialization. This is similar to the existing cases you found where you could pass NULL to the constructor, and later go back to initialize the object.

    Edit:

    I thought of this earlier (even though it looks much like other people's solutions). But I had to get some confirmation that this wouldn't break before I added this solution - C++ can be quite tricky, and I don't use it very often :)

    This is cleaner than my other suggestions, and doesn't require you to mess with any implementation but that of A.

    Simply use a static method as the middle-man on your initialization:

    class A
    {
    public:
        A();
    
    private:
        static int InitFromB(B& b)
        {
            b.doSomething();
            b.doMore();
            return b.getSomeValue();
        }
    
        // m_B must be initialized before m_C
        B m_B;
        C m_C;
    };
    
    A::A()
        : m_B(1)
        , m_C(InitFromB(m_B))
    {
    }
    

    Note that this means you can't allow m_B to depend on the instance of A or C at all, whereas the solutions at the top of this answer might allow you to pass A or m_C into m_B's methods.

提交回复
热议问题