Avoid calling constructor of member variable

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

    The pointer sounds like the only clean solution to me. The only other solution I see is to have a default constructor for C that does nothing and have an initialising method in C you call yourself later.

    m_C.Initialise( m_B.getSomeValue() );

    0 讨论(0)
  • 2021-02-19 14:18

    Easiest is storing pointers to a B and a C. These can be initialized to 0, omitting any construction. Be careful not to dereference a null pointer and delete it in the destructor of A (or use std::unique_ptr/boost::scoped_ptr).

    But why not initialize m_B first (through a proper constructor call, not in A::A(), and then use that initialized B instance to initialize m_C? It will call for a small rewrite, but I bet it'll be worth the code cleanup.

    0 讨论(0)
  • 2021-02-19 14:19

    What you ask is forbidden - and correctly so. This ensures that every member is correctly initialized. Do not try to work around it - try to structure your classes that they work with it.

    Idea:

    • C has a constructor that does nothing
    • C has an initialization method that makes the class usable
    • C tracks whether it has been initialized correctly or not and returns appropriate errors if used without initialization.
    0 讨论(0)
提交回复
热议问题