Calling member functions from a constructor

后端 未结 5 886
我在风中等你
我在风中等你 2020-12-29 08:17

I know this question has a similar title to this: C++: calling member functions within constructor? but I am asking a more general question.

Is it good practice to c

5条回答
  •  攒了一身酷
    2020-12-29 08:58

    There is at least one associated "gotcha" you should be aware of:

    N3797 12.6.2/14

    Member functions (including virtual member functions, 10.3) can be called for an object under construction. Similarly, an object under construction can be the operand of the typeid operator (5.2.8) or of a dynamic_cast (5.2.7). However, if these operations are performed in a ctor-initializer (or in a function called directly or indirectly from a ctor-initializer) before all the mem-initializers for base classes have completed, the result of the operation is undefined. [Example:

    class A {
    public:
       A(int);
    };
    
    class B : public A {
        int j;
    public:
        int f();
        B() : A(f()),  // undefined: calls member function
                       // but base A not yet initialized
        j(f()) { }     // well-defined: bases are all initialized
    };
    
    class C {
    public:
        C(int);
    };
    
    class D : public B, C {
        int i;
    public:
        D() : C(f()), // undefined: calls member function
                      // but base C not yet initialized
        i(f()) { }    // well-defined: bases are all initialized
    };
    

    — end example]

提交回复
热议问题