Avoid calling constructor of member variable

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

    How about using technique described in this QA?

    Prevent calls to default constructor for an array inside class

    std::aligned_storage::type
    

    Or, you also can consider using of union. AFAIK, unions will be initialized only with first named member's constructor.

    For example,

    union
    {
       uint8_t _nothing = 0; 
       C c;
    };
    

    According to the standard mentioned in the QA, c will be zero-initialized, and its constructor will not be called.

提交回复
热议问题