构造函数语义学——Default Constructor篇

构造函数语义学——Default Constructor 篇

这一章原书主要分析了:编译器关于对象构造过程的干涉,即在对象构造这个过程中,编译器到底在背后做了什么

这一章的重点在于 default constructor 和 copy constructor 的相关知识

Default Constructor 详解

一些 C++的书籍中告诉我们:如果不写任何构造函数,那么编译器会为我们生成一个默认构造函数(default constructor)

那么,针对这个观点,有两个问题:

  • 这句话是正确的吗?
  • 如果这句话是正确的,那么编译器为我们生成的 default constructor 里有什么动作吗?

1 这句话是正确的吗?

这句话大体是正确的,但是 cppreference 中有更详细的说明:

若不对类类型(struct、class 或 union)提供任何用户声明的构造函数,则编译器将始终声明一个作为其类的 inline public 成员的默认构造函数。
当存在用户声明的构造函数时,用户仍可以关键词 default 强制编译器自动生成原本隐式声明的默认构造函数。

上面这段话告诉我们:只有在没有任何用户声明的构造函数的情况下,编译器才会声明一个 default constructor。换言之,只要有任何用户声明的构造函数(不一定要是 default constructor),哪怕该构造函数不是 default constructor,那么编译器就不会为我们生成 default constructor(除了强制编译器生成)

隐式定义的默认构造函数
若隐式声明的默认构造函数未被定义为弃置的,则当其被 ODR 式使用时,它为编译器所定义(即生成函数体并编译之),且它与拥有空函数体和空初始化器列表的用户定义的构造函数有严格相同的效果。即它调用这个类的各基类和各非静态成员的默认构造函数

有没有什么证据能证明编译器真的隐式定义了一个默认构造函数呢?有,考虑如下的一个类:

class A {};

这个类中没有任何成员变量或者成员函数,此时打印出该类的相关信息如下:

// clang -cc1 -fdump-record-layouts -emit-llvm main.cpp 命令
*** Dumping AST Record Layout
         0 | class A (empty)
           | [sizeof=1, dsize=1, align=1,
           |  nvsize=1, nvalign=1]

*** Dumping IRgen Record Layout
Record: CXXRecordDecl 0x55c6626abc70 <main.cpp:1:1, line:3:1> line:1:7 referenced class A definition
|-DefinitionData pass_in_registers empty aggregate standard_layout trivially_copyable pod trivial literal has_constexpr_non_copy_move_ctor can_const_default_init
| |-DefaultConstructor exists trivial constexpr defaulted_is_constexpr
| |-CopyConstructor simple trivial has_const_param implicit_has_const_param
| |-MoveConstructor exists simple trivial
| |-CopyAssignment trivial has_const_param needs_implicit implicit_has_const_param
| |-MoveAssignment exists simple trivial needs_implicit
| `-Destructor simple irrelevant trivial needs_implicit
|-CXXRecordDecl 0x55c6626abd88 <col:1, col:7> col:7 implicit class A
|-CXXConstructorDecl 0x55c6626ac020 <col:7> col:7 implicit used constexpr A 'void () noexcept' inline default trivial
| `-CompoundStmt 0x55c6626ac4b8 <col:7>
|-CXXConstructorDecl 0x55c6626ac158 <col:7> col:7 implicit constexpr A 'void (const A &)' inline default trivial noexcept-unevaluated 0x55c6626ac158
| `-ParmVarDecl 0x55c6626ac268 <col:7> col:7 'const A &'
`-CXXConstructorDecl 0x55c6626ac308 <col:7> col:7 implicit constexpr A 'void (A &&)' inline default trivial noexcept-unevaluated 0x55c6626ac308
  `-ParmVarDecl 0x55c6626ac418 <col:7> col:7 'A &&'

Layout: <CGRecordLayout
  LLVMType:%class.A = type { i8 }
  NonVirtualBaseLLVMType:%class.A = type { i8 }
  IsZeroInitializable:1
  BitFields:[
]>

DefaultConstructor exists trivial constexpr defaulted_is_constexpr这一行证明了这个类存在一个 default constructor 且是 trivial 的,而我们并没有声明和定义,那么自然是编译器为我们自动生成的

2 隐式定义的默认构造函数里发生了什么?

在解决这个问题之前,首先有需要了解一些额外的知识:

default constructor 是分为 trivial default constructor(平凡默认构造函数,即不进行任何构造动作)和 non trivial default constructor(非平凡默认构造函数)

什么情况下 default constructor 是 trivial 的呢?cppreference 中说明了这一点:

当下列各项全部为真时,类 T 的默认构造函数为平凡的(平凡默认构造函数是不进行任何动作的构造函数。):
构造函数并非用户提供(即为隐式定义或于其首个声明中预置的)
T 没有虚成员函数
T 没有虚基类
T 没有拥有默认初始化器的非静态数据成员。
每个 T 的直接基类都拥有平凡默认构造函数
每个类类型的非静态成员都拥有平凡默认构造函数

注意上述条件中的第一点也说明了一个事实:如果构造函数是用户定义的,那么必定是非平凡的

再回到隐式定义的默认构造函数里发生了什么?这个问题,就需要从两个角度来考虑了:

  1. 当编译器隐式定义的默认构造函数是一个 trivial default constructor 时,那么该 trivial default constructor 什么也不做
  2. 那么当编译器隐式定义的默认构造函数是一个 non-trivial default constructor 时,该 non-trivial default constructor 调用这个类的各基类和各非静态成员的默认构造函数

通过以上,我们已经知道了编译器在特定情况下,真的会隐式定义一个 default constructor,也知道了在哪些情况下产生的 default constructor 是 trivial 的,那么再来详细的讨论一下,什么情况下,编译器生成的 default constructor 是 non-trivial 的

  1. 带有 default constructor 的 member class object

    如果一个 class A 没有任何的 constructor,但是它内含一个 member object,而该 member object 拥有 non-trivial default constructor,那么编译器为这个 class 隐式定义的 default constructor 是 non-trivial。为什么呢?因为编译器为该 class A 产生的 default constructor 里必须要调用 member object 的 non-trivial default constructor,否则无法完整的构造 class A 的对象

    仍然用代码来证明:

    class B {
     private:
      int b;
     public:
      B() {}
    };
    
    class A {
     private:
      B b;
    	int a;
    };
    

    打印出 class A 的相关信息,如下:

    *** Dumping AST Record Layout
             0 | class B
             0 |   int b
               | [sizeof=4, dsize=4, align=4,
               |  nvsize=4, nvalign=4]
    
    *** Dumping AST Record Layout
             0 | class A
             0 |   class B b
             0 |     int b
             4 |   int a
               | [sizeof=8, dsize=8, align=4,
               |  nvsize=8, nvalign=4]
    
    *** Dumping IRgen Record Layout
    Record: CXXRecordDecl 0x55ba37562c50 <main.cpp:1:1, line:6:1> line:1:7 referenced class B definition
    |-DefinitionData pass_in_registers standard_layout trivially_copyable has_user_declared_ctor can_const_default_init
    | |-DefaultConstructor exists non_trivial user_provided
    | |-CopyConstructor simple trivial has_const_param implicit_has_const_param
    | |-MoveConstructor exists simple trivial
    | |-CopyAssignment trivial has_const_param needs_implicit implicit_has_const_param
    | |-MoveAssignment exists simple trivial needs_implicit
    | `-Destructor simple irrelevant trivial
    |-CXXRecordDecl 0x55ba37562d68 <col:1, col:7> col:7 implicit referenced class B
    |-AccessSpecDecl 0x55ba37562df8 <line:2:2, col:9> col:2 private
    |-FieldDecl 0x55ba37562e38 <line:3:3, col:7> col:7 b 'int'
    |-AccessSpecDecl 0x55ba37562e88 <line:4:2, col:8> col:2 public
    |-CXXConstructorDecl 0x55ba37562f38 <line:5:3, col:8> col:3 used B 'void ()'
    | `-CompoundStmt 0x55ba37562ff8 <col:7, col:8>
    |-CXXDestructorDecl 0x55ba37563590 <line:1:7> col:7 implicit ~B 'void ()' inline default trivial noexcept-unevaluated 0x55ba37563590
    |-CXXConstructorDecl 0x55ba375636c8 <col:7> col:7 implicit constexpr B 'void (const B &)' inline default trivial noexcept-unevaluated 0x55ba375636c8
    | `-ParmVarDecl 0x55ba375637d8 <col:7> col:7 'const B &'
    `-CXXConstructorDecl 0x55ba37563878 <col:7> col:7 implicit constexpr B 'void (B &&)' inline default trivial noexcept-unevaluated 0x55ba37563878
      `-ParmVarDecl 0x55ba37563988 <col:7> col:7 'B &&'
    
    Layout: <CGRecordLayout
      LLVMType:%class.B = type { i32 }
      NonVirtualBaseLLVMType:%class.B = type { i32 }
      IsZeroInitializable:1
      BitFields:[
    ]>
    
    *** Dumping IRgen Record Layout
    Record: CXXRecordDecl 0x55ba37563008 <main.cpp:8:1, line:12:1> line:8:7 referenced class A definition
    |-DefinitionData pass_in_registers standard_layout trivially_copyable
    | |-DefaultConstructor exists non_trivial
    | |-CopyConstructor simple trivial has_const_param implicit_has_const_param
    | |-MoveConstructor exists simple trivial
    | |-CopyAssignment trivial has_const_param needs_implicit implicit_has_const_param
    | |-MoveAssignment exists simple trivial needs_implicit
    | `-Destructor simple irrelevant trivial needs_implicit
    |-CXXRecordDecl 0x55ba37563128 <col:1, col:7> col:7 implicit class A
    |-AccessSpecDecl 0x55ba375631b8 <line:9:2, col:9> col:2 private
    |-FieldDecl 0x55ba375631f0 <line:10:3, col:5> col:5 b 'B'
    |-FieldDecl 0x55ba37563258 <line:11:3, col:7> col:7 a 'int'
    |-CXXConstructorDecl 0x55ba375634b0 <line:8:7> col:7 implicit used A 'void () noexcept(false)' inline default
    | |-CXXCtorInitializer Field 0x55ba375631f0 'b' 'B'
    | | `-CXXConstructExpr 0x55ba37592090 <col:7> 'B' 'void ()'
    | `-CompoundStmt 0x55ba375920e8 <col:7>
    |-CXXConstructorDecl 0x55ba375639f8 <col:7> col:7 implicit constexpr A 'void (const A &)' inline default trivial noexcept-unevaluated 0x55ba375639f8
    | `-ParmVarDecl 0x55ba37591e30 <col:7> col:7 'const A &'
    `-CXXConstructorDecl 0x55ba37591ec8 <col:7> col:7 implicit constexpr A 'void (A &&)' inline default trivial noexcept-unevaluated 0x55ba37591ec8
      `-ParmVarDecl 0x55ba37591fd8 <col:7> col:7 'A &&'
    
    Layout: <CGRecordLayout
      LLVMType:%class.A = type { %class.B, i32 }
      NonVirtualBaseLLVMType:%class.A = type { %class.B, i32 }
      IsZeroInitializable:1
      BitFields:[
    ]>
    
    DefaultConstructor exists non_trivial user_provided
    

    这一行中说明 class B 是用户定义的一个 default constructor,是 non-trivial 的

    DefaultConstructor exists non_trivial
    

    第二行中则说明 class A 的 default constructor 也是存在的且是 non-trivial 的。在这个 non-trivial default constructor 中,编译器会调用 class B 的 default constructor 来初始化 class A 的对象中的 b 成分,但是不会初始化 a(编译器看来,初始化 b 是它的工作,但是初始化 a 是程序员的工作)

    |-CXXConstructorDecl 0x55ba375634b0 <line:8:7> col:7 implicit used A 'void () noexcept(false)' inline default
    | |-CXXCtorInitializer Field 0x55ba375631f0 'b' 'B'
    | | `-CXXConstructExpr 0x55ba37592090 <col:7> 'B' 'void ()'
    | `-CompoundStmt 0x55ba375920e8 <col:7>
    

    这一段则说明了在 class A 的 default constructor 中调用了 class B 的 default constructor

    如果,class A 中提供了一个 default constructor,那么编译器会怎么办呢?

    class B {
     private:
      int b;
     public:
      B() {}
    };
    
    class A {
     private:
      B b;
      int a;
     public:
      A() {
        a = 0;
      }
    };
    

    打印相关信息如下:

    *** Dumping AST Record Layout
             0 | class B
             0 |   int b
               | [sizeof=4, dsize=4, align=4,
               |  nvsize=4, nvalign=4]
    
    *** Dumping AST Record Layout
             0 | class A
             0 |   class B b
             0 |     int b
             4 |   int a
               | [sizeof=8, dsize=8, align=4,
               |  nvsize=8, nvalign=4]
    
    *** Dumping IRgen Record Layout
    Record: CXXRecordDecl 0x5641e5965d20 <main.cpp:1:1, line:6:1> line:1:7 referenced class B definition
    |-DefinitionData pass_in_registers standard_layout trivially_copyable has_user_declared_ctor can_const_default_init
    | |-DefaultConstructor exists non_trivial user_provided
    | |-CopyConstructor simple trivial has_const_param implicit_has_const_param
    | |-MoveConstructor exists simple trivial
    | |-CopyAssignment trivial has_const_param needs_implicit implicit_has_const_param
    | |-MoveAssignment exists simple trivial needs_implicit
    | `-Destructor simple irrelevant trivial
    |-CXXRecordDecl 0x5641e5965e38 <col:1, col:7> col:7 implicit referenced class B
    |-AccessSpecDecl 0x5641e5965ec8 <line:2:2, col:9> col:2 private
    |-FieldDecl 0x5641e5965f08 <line:3:3, col:7> col:7 b 'int'
    |-AccessSpecDecl 0x5641e5965f58 <line:4:2, col:8> col:2 public
    |-CXXConstructorDecl 0x5641e5966008 <line:5:3, col:8> col:3 used B 'void ()'
    | `-CompoundStmt 0x5641e59660c8 <col:7, col:8>
    |-CXXConstructorDecl 0x5641e59664e8 <line:1:7> col:7 implicit constexpr B 'void (const B &)' inline default trivial noexcept-unevaluated 0x5641e59664e8
    | `-ParmVarDecl 0x5641e59665f8 <col:7> col:7 'const B &'
    |-CXXConstructorDecl 0x5641e5966698 <col:7> col:7 implicit constexpr B 'void (B &&)' inline default trivial noexcept-unevaluated 0x5641e5966698
    | `-ParmVarDecl 0x5641e59667a8 <col:7> col:7 'B &&'
    `-CXXDestructorDecl 0x5641e59953b8 <col:7> col:7 implicit ~B 'void ()' inline default trivial noexcept-unevaluated 0x5641e59953b8
    
    Layout: <CGRecordLayout
      LLVMType:%class.B = type { i32 }
      NonVirtualBaseLLVMType:%class.B = type { i32 }
      IsZeroInitializable:1
      BitFields:[
    ]>
    
    *** Dumping IRgen Record Layout
    Record: CXXRecordDecl 0x5641e59660d8 <main.cpp:8:1, line:16:1> line:8:7 referenced class A definition
    |-DefinitionData pass_in_registers standard_layout trivially_copyable has_user_declared_ctor can_const_default_init
    | |-DefaultConstructor exists non_trivial user_provided
    | |-CopyConstructor simple trivial has_const_param implicit_has_const_param
    | |-MoveConstructor exists simple trivial
    | |-CopyAssignment trivial has_const_param needs_implicit implicit_has_const_param
    | |-MoveAssignment exists simple trivial needs_implicit
    | `-Destructor simple irrelevant trivial needs_implicit
    |-CXXRecordDecl 0x5641e59661f8 <col:1, col:7> col:7 implicit referenced class A
    |-AccessSpecDecl 0x5641e5966288 <line:9:2, col:9> col:2 private
    |-FieldDecl 0x5641e59662c0 <line:10:3, col:5> col:5 b 'B'
    |-FieldDecl 0x5641e5966328 <line:11:3, col:7> col:7 referenced a 'int'
    |-AccessSpecDecl 0x5641e5966378 <line:12:2, col:8> col:2 public
    |-CXXConstructorDecl 0x5641e5966400 <line:13:3, line:15:3> line:13:3 used A 'void ()'
    | |-CXXCtorInitializer Field 0x5641e59662c0 'b' 'B'
    | | `-CXXConstructExpr 0x5641e5966818 <col:3> 'B' 'void ()'
    | `-CompoundStmt 0x5641e59668f0 <col:7, line:15:3>
    |   `-BinaryOperator 0x5641e59668d0 <line:14:5, col:9> 'int' lvalue '='
    |     |-MemberExpr 0x5641e5966880 <col:5> 'int' lvalue ->a 0x5641e5966328
    |     | `-CXXThisExpr 0x5641e5966870 <col:5> 'A *' implicit this
    |     `-IntegerLiteral 0x5641e59668b0 <col:9> 'int' 0
    |-CXXConstructorDecl 0x5641e5966b18 <line:8:7> col:7 implicit constexpr A 'void (const A &)' inline default trivial noexcept-unevaluated 0x5641e5966b18
    | `-ParmVarDecl 0x5641e5995348 <col:7> col:7 'const A &'
    `-CXXConstructorDecl 0x5641e59954c8 <col:7> col:7 implicit constexpr A 'void (A &&)' inline default trivial noexcept-unevaluated 0x5641e59954c8
      `-ParmVarDecl 0x5641e59955d8 <col:7> col:7 'A &&'
    
    Layout: <CGRecordLayout
      LLVMType:%class.A = type { %class.B, i32 }
      NonVirtualBaseLLVMType:%class.A = type { %class.B, i32 }
      IsZeroInitializable:1
      BitFields:[
    ]>
    
    |-CXXConstructorDecl 0x5641e5966400 <line:13:3, line:15:3> line:13:3 used A 'void ()'
    | |-CXXCtorInitializer Field 0x5641e59662c0 'b' 'B'
    | | `-CXXConstructExpr 0x5641e5966818 <col:3> 'B' 'void ()'
    

    可以发现,在我们定义的 default constructor 中,也调用了 class B 的 default constructor,且这个调用动作发生在 a = 0;这条语句之前,然而我们并没有写呀,这便是编译器自动安插的调用

    也就是说,在这种情况下,编译器会扩充已经存在 constructor,在其中安插一些代码,使得在该 constgructor 中所有代码执行之前,先调用必要的 default constructor

    如果 class A 提供了其他的 constructors,但是没有提供 default constructor,那么编译器还会为我们生成 default consturctor 吗?

    这个之前已经说过了,答案是不会。依然用事实证明:

    class B {
     private:
      int b;
     public:
      B() {}
    };
    
    class A {
     private:
      B b;
      int a;
     public:
      A(int _a) : a(_a) {}
    };
    
    int main() {
      A a(1);
    }
    
    *** Dumping AST Record Layout
             0 | class B
             0 |   int b
               | [sizeof=4, dsize=4, align=4,
               |  nvsize=4, nvalign=4]
    
    *** Dumping AST Record Layout
             0 | class A
             0 |   class B b
             0 |     int b
             4 |   int a
               | [sizeof=8, dsize=8, align=4,
               |  nvsize=8, nvalign=4]
    
    *** Dumping IRgen Record Layout
    Record: CXXRecordDecl 0x55df47367d20 <main.cpp:1:1, line:6:1> line:1:7 referenced class B definition
    |-DefinitionData pass_in_registers standard_layout trivially_copyable has_user_declared_ctor can_const_default_init
    | |-DefaultConstructor exists non_trivial user_provided
    | |-CopyConstructor simple trivial has_const_param implicit_has_const_param
    | |-MoveConstructor exists simple trivial
    | |-CopyAssignment trivial has_const_param needs_implicit implicit_has_const_param
    | |-MoveAssignment exists simple trivial needs_implicit
    | `-Destructor simple irrelevant trivial
    |-CXXRecordDecl 0x55df47367e38 <col:1, col:7> col:7 implicit referenced class B
    |-AccessSpecDecl 0x55df47367ec8 <line:2:2, col:9> col:2 private
    |-FieldDecl 0x55df47367f08 <line:3:3, col:7> col:7 b 'int'
    |-AccessSpecDecl 0x55df47367f58 <line:4:2, col:8> col:2 public
    |-CXXConstructorDecl 0x55df47368008 <line:5:3, col:8> col:3 used B 'void ()'
    | `-CompoundStmt 0x55df473680c8 <col:7, col:8>
    |-CXXConstructorDecl 0x55df47368628 <line:1:7> col:7 implicit constexpr B 'void (const B &)' inline default trivial noexcept-unevaluated 0x55df47368628
    | `-ParmVarDecl 0x55df47368738 <col:7> col:7 'const B &'
    |-CXXConstructorDecl 0x55df473687d8 <col:7> col:7 implicit constexpr B 'void (B &&)' inline default trivial noexcept-unevaluated 0x55df473687d8
    | `-ParmVarDecl 0x55df473688e8 <col:7> col:7 'B &&'
    `-CXXDestructorDecl 0x55df473978a8 <col:7> col:7 implicit ~B 'void ()' inline default trivial noexcept-unevaluated 0x55df473978a8
    
    Layout: <CGRecordLayout
      LLVMType:%class.B = type { i32 }
      NonVirtualBaseLLVMType:%class.B = type { i32 }
      IsZeroInitializable:1
      BitFields:[
    ]>
    
    *** Dumping IRgen Record Layout
    Record: CXXRecordDecl 0x55df473680d8 <main.cpp:8:1, line:14:1> line:8:7 referenced class A definition
    |-DefinitionData pass_in_registers standard_layout trivially_copyable has_user_declared_ctor can_const_default_init
    | |-DefaultConstructor
    | |-CopyConstructor simple trivial has_const_param implicit_has_const_param
    | |-MoveConstructor exists simple trivial
    | |-CopyAssignment trivial has_const_param needs_implicit implicit_has_const_param
    | |-MoveAssignment exists simple trivial needs_implicit
    | `-Destructor simple irrelevant trivial needs_implicit
    |-CXXRecordDecl 0x55df473681f8 <col:1, col:7> col:7 implicit referenced class A
    |-AccessSpecDecl 0x55df47368288 <line:9:2, col:9> col:2 private
    |-FieldDecl 0x55df473682c0 <line:10:3, col:5> col:5 b 'B'
    |-FieldDecl 0x55df47368328 <line:11:3, col:7> col:7 a 'int'
    |-AccessSpecDecl 0x55df47368378 <line:12:2, col:8> col:2 public
    |-CXXConstructorDecl 0x55df473684b8 <line:13:3, col:22> col:3 used A 'void (int)'
    | |-ParmVarDecl 0x55df473683b8 <col:5, col:9> col:9 used _a 'int'
    | |-CXXCtorInitializer Field 0x55df473682c0 'b' 'B'
    | | `-CXXConstructExpr 0x55df47368958 <col:3> 'B' 'void ()'
    | |-CXXCtorInitializer Field 0x55df47368328 'a' 'int'
    | | `-ImplicitCastExpr 0x55df473685c0 <col:17> 'int' <LValueToRValue>
    | |   `-DeclRefExpr 0x55df47368580 <col:17> 'int' lvalue ParmVar 0x55df473683b8 '_a' 'int'
    | `-CompoundStmt 0x55df473689b8 <col:21, col:22>
    |-CXXConstructorDecl 0x55df47397720 <line:8:7> col:7 implicit constexpr A 'void (const A &)' inline default trivial noexcept-unevaluated 0x55df47397720
    | `-ParmVarDecl 0x55df47397838 <col:7> col:7 'const A &'
    `-CXXConstructorDecl 0x55df473979b8 <col:7> col:7 implicit constexpr A 'void (A &&)' inline default trivial noexcept-unevaluated 0x55df473979b8
      `-ParmVarDecl 0x55df47397ac8 <col:7> col:7 'A &&'
    
    Layout: <CGRecordLayout
      LLVMType:%class.A = type { %class.B, i32 }
      NonVirtualBaseLLVMType:%class.A = type { %class.B, i32 }
      IsZeroInitializable:1
      BitFields:[
    ]>
    
    Record: CXXRecordDecl 0x55df473680d8 <main.cpp:8:1, line:14:1> line:8:7 referenced class A definition
    |-DefinitionData pass_in_registers standard_layout trivially_copyable has_user_declared_ctor can_const_default_init
    | |-DefaultConstructor
    

    这几行证明了,编译器没有为 class A 生成 default constructor

    |-CXXConstructorDecl 0x55df473684b8 <line:13:3, col:22> col:3 used A 'void (int)'
    | |-ParmVarDecl 0x55df473683b8 <col:5, col:9> col:9 used _a 'int'
    | |-CXXCtorInitializer Field 0x55df473682c0 'b' 'B'
    | | `-CXXConstructExpr 0x55df47368958 <col:3> 'B' 'void ()'
    

    这几行证明了编译器扩充了 A 的单参数 constructor,在里面安插了对 B 的 default consturctor 的调用

  2. 带有 default constructor 的 Base class

    如果一个没有任何user_provided constructors的class派生自一个带有default constructor的base class,那么这个 dervied class 的 default constructor 会被编译器自动合成出来且是 non-trivial 的

    一个需要注意的地方是,上述成立的一个充分不必要条件是:base class 的 default constructor 只有是 non-tirvial 时,dervied class 被合成的这个 default constructor 才是 non-trivial 的;具体原因可以回顾一下之前所说的平凡默认构造函数的所需条件

    同理,如果 derived class 提供了 defualt constructor 或者其他 constructors 的话,其结果也与第 1 点中所述情况类似,读者可以自行实验

  3. 带有一个 virtual function 的 class

    如果一个没有任何user_provided constructors的class中声明(或继承)了一个virtual function,那么编译器会自动为该 class 生成一个 default constructor,且该 defalut constructor 是 non-trivial 的

    举例证明:

    // 定义了一个virtual function
    class A {
     public:
      virtual void vfunc() {}
    };
    
    // 继承了一个virtual function
    class B: public A {
    };
    

    打印相关信息:

    *** Dumping AST Record Layout
             0 | class A
             0 |   (A vtable pointer)
               | [sizeof=8, dsize=8, align=8,
               |  nvsize=8, nvalign=8]
    
    *** Dumping AST Record Layout
             0 | class B
             0 |   class A (primary base)
             0 |     (A vtable pointer)
               | [sizeof=8, dsize=8, align=8,
               |  nvsize=8, nvalign=8]
    
    *** Dumping IRgen Record Layout
    Record: CXXRecordDecl 0x55d1c6dc4c50 <main.cpp:1:1, line:4:1> line:1:7 referenced class A definition
    |-DefinitionData polymorphic literal has_constexpr_non_copy_move_ctor can_const_default_init
    | |-DefaultConstructor exists non_trivial constexpr defaulted_is_constexpr
    | |-CopyConstructor simple non_trivial has_const_param implicit_has_const_param
    | |-MoveConstructor exists simple non_trivial
    | |-CopyAssignment non_trivial has_const_param implicit_has_const_param
    | |-MoveAssignment exists simple non_trivial
    | `-Destructor simple irrelevant trivial
    |-CXXRecordDecl 0x55d1c6dc4d68 <col:1, col:7> col:7 implicit class A
    |-AccessSpecDecl 0x55d1c6dc4df8 <line:2:2, col:8> col:2 public
    |-CXXMethodDecl 0x55d1c6dc4e98 <line:3:3, col:25> col:16 vfunc 'void ()' virtual
    | `-CompoundStmt 0x55d1c6dc53c0 <col:24, col:25>
    |-CXXMethodDecl 0x55d1c6dc4f98 <line:1:7> col:7 implicit constexpr operator= 'A &(const A &)' inline default noexcept-unevaluated 0x55d1c6dc4f98
    | `-ParmVarDecl 0x55d1c6dc50a8 <col:7> col:7 'const A &'
    |-CXXMethodDecl 0x55d1c6dc5148 <col:7> col:7 implicit constexpr operator= 'A &(A &&)' inline default noexcept-unevaluated 0x55d1c6dc5148
    | `-ParmVarDecl 0x55d1c6dc5258 <col:7> col:7 'A &&'
    |-CXXDestructorDecl 0x55d1c6dc52e0 <col:7> col:7 implicit ~A 'void ()' inline default trivial noexcept-unevaluated 0x55d1c6dc52e0
    |-CXXConstructorDecl 0x55d1c6df4028 <col:7> col:7 implicit used constexpr A 'void () noexcept' inline default
    | `-CompoundStmt 0x55d1c6df4738 <col:7>
    |-CXXConstructorDecl 0x55d1c6df4100 <col:7> col:7 implicit constexpr A 'void (const A &)' inline default noexcept-unevaluated 0x55d1c6df4100
    | `-ParmVarDecl 0x55d1c6df4218 <col:7> col:7 'const A &'
    `-CXXConstructorDecl 0x55d1c6df4288 <col:7> col:7 implicit constexpr A 'void (A &&)' inline default noexcept-unevaluated 0x55d1c6df4288
      `-ParmVarDecl 0x55d1c6df4398 <col:7> col:7 'A &&'
    
    Layout: <CGRecordLayout
      LLVMType:%class.A = type { i32 (...)** }
      NonVirtualBaseLLVMType:%class.A = type { i32 (...)** }
      IsZeroInitializable:1
      BitFields:[
    ]>
    
    *** Dumping IRgen Record Layout
    Record: CXXRecordDecl 0x55d1c6dc53d0 <main.cpp:7:1, line:8:1> line:7:7 referenced class B definition
    |-DefinitionData polymorphic literal has_constexpr_non_copy_move_ctor can_const_default_init
    | |-DefaultConstructor exists non_trivial constexpr defaulted_is_constexpr
    | |-CopyConstructor simple non_trivial has_const_param implicit_has_const_param
    | |-MoveConstructor exists simple non_trivial
    | |-CopyAssignment non_trivial has_const_param implicit_has_const_param
    | |-MoveAssignment exists simple non_trivial
    | `-Destructor simple irrelevant trivial
    |-public 'A'
    |-CXXRecordDecl 0x55d1c6dc5528 <col:1, col:7> col:7 implicit class B
    |-CXXMethodDecl 0x55d1c6dc5618 <col:7> col:7 implicit constexpr operator= 'B &(const B &)' inline default noexcept-unevaluated 0x55d1c6dc5618
    | `-ParmVarDecl 0x55d1c6dc5728 <col:7> col:7 'const B &'
    |-CXXMethodDecl 0x55d1c6dc57c8 <col:7> col:7 implicit constexpr operator= 'B &(B &&)' inline default noexcept-unevaluated 0x55d1c6dc57c8
    | `-ParmVarDecl 0x55d1c6dc58d8 <col:7> col:7 'B &&'
    |-CXXDestructorDecl 0x55d1c6dc5960 <col:7> col:7 implicit ~B 'void ()' inline default trivial noexcept-unevaluated 0x55d1c6dc5960
    |-CXXConstructorDecl 0x55d1c6df3f30 <col:7> col:7 implicit used constexpr B 'void () noexcept' inline default
    | |-CXXCtorInitializer 'A'
    | | `-CXXConstructExpr 0x55d1c6df4748 <col:7> 'A' 'void () noexcept'
    | `-CompoundStmt 0x55d1c6df47b0 <col:7>
    |-CXXConstructorDecl 0x55d1c6df4408 <col:7> col:7 implicit constexpr B 'void (const B &)' inline default noexcept-unevaluated 0x55d1c6df4408
    | `-ParmVarDecl 0x55d1c6df4518 <col:7> col:7 'const B &'
    `-CXXConstructorDecl 0x55d1c6df4588 <col:7> col:7 implicit constexpr B 'void (B &&)' inline default noexcept-unevaluated 0x55d1c6df4588
      `-ParmVarDecl 0x55d1c6df4698 <col:7> col:7 'B &&'
    
    Layout: <CGRecordLayout
      LLVMType:%class.B = type { %class.A }
      NonVirtualBaseLLVMType:%class.B = type { %class.A }
      IsZeroInitializable:1
      BitFields:[
    ]>
    
    Record: CXXRecordDecl 0x55d1c6dc4c50 <main.cpp:1:1, line:4:1> line:1:7 referenced class A definition
    |-DefinitionData polymorphic literal has_constexpr_non_copy_move_ctor can_const_default_init
    | |-DefaultConstructor exists non_trivial constexpr defaulted_is_constexpr
    
    Record: CXXRecordDecl 0x55d1c6dc53d0 <main.cpp:7:1, line:8:1> line:7:7 referenced class B definition
    |-DefinitionData polymorphic literal has_constexpr_non_copy_move_ctor can_const_default_init
    | |-DefaultConstructor exists non_trivial constexpr defaulted_is_constexpr
    

    这几行证明了之前的所述的观点

    与之前的情况不同的时,这种情况下所生成的 default constructor,不仅需要调用必须的基类的 default constructor,还需要完成设定 vptr 的动作,才能满足虚机制的运行

    与之前相同的是,如果提供了任何用户声明的 constructors,那么自然不会生成 default constructor,编译器会对现有的 constrcutors 进行扩充,来完成必要的工作

    还是举个例子吧:

    class A {
     public:
      virtual void vfunc() {}
      A(int a) : _a(a) {}
     private:
      int _a;
    };
    
    class B : public A {
     public:
      B(int a, int b) : A(a), _b(b) {}
     private:
      int _b;
    };
    

    打印相关信息:

    *** Dumping AST Record Layout
             0 | class A
             0 |   (A vtable pointer)
             8 |   int _a
               | [sizeof=16, dsize=12, align=8,
               |  nvsize=12, nvalign=8]
    
    *** Dumping AST Record Layout
             0 | class B
             0 |   class A (primary base)
             0 |     (A vtable pointer)
             8 |     int _a
            12 |   int _b
               | [sizeof=16, dsize=16, align=8,
               |  nvsize=16, nvalign=8]
    
    *** Dumping IRgen Record Layout
    Record: CXXRecordDecl 0x56506d274d60 <main.cpp:1:1, line:7:1> line:1:7 referenced class A definition
    |-DefinitionData polymorphic has_user_declared_ctor can_const_default_init
    | |-DefaultConstructor
    | |-CopyConstructor simple non_trivial has_const_param implicit_has_const_param
    | |-MoveConstructor exists simple non_trivial
    | |-CopyAssignment non_trivial has_const_param implicit_has_const_param
    | |-MoveAssignment exists simple non_trivial
    | `-Destructor simple irrelevant trivial
    |-CXXRecordDecl 0x56506d274e78 <col:1, col:7> col:7 implicit referenced class A
    |-AccessSpecDecl 0x56506d274f08 <line:2:2, col:8> col:2 public
    |-CXXMethodDecl 0x56506d274fa8 <line:3:3, col:25> col:16 vfunc 'void ()' virtual
    | `-CompoundStmt 0x56506d275700 <col:24, col:25>
    |-CXXConstructorDecl 0x56506d275138 <line:4:3, col:21> col:3 used A 'void (int)'
    | |-ParmVarDecl 0x56506d275060 <col:5, col:9> col:9 used a 'int'
    | |-CXXCtorInitializer Field 0x56506d275228 '_a' 'int'
    | | `-ImplicitCastExpr 0x56506d275750 <col:17> 'int' <LValueToRValue>
    | |   `-DeclRefExpr 0x56506d275710 <col:17> 'int' lvalue ParmVar 0x56506d275060 'a' 'int'
    | `-CompoundStmt 0x56506d275798 <col:20, col:21>
    |-AccessSpecDecl 0x56506d2751e8 <line:5:2, col:9> col:2 private
    |-FieldDecl 0x56506d275228 <line:6:3, col:7> col:7 _a 'int'
    |-CXXMethodDecl 0x56506d2752d8 <line:1:7> col:7 implicit operator= 'A &(const A &)' inline default noexcept-unevaluated 0x56506d2752d8
    | `-ParmVarDecl 0x56506d2753e8 <col:7> col:7 'const A &'
    |-CXXMethodDecl 0x56506d275488 <col:7> col:7 implicit operator= 'A &(A &&)' inline default noexcept-unevaluated 0x56506d275488
    | `-ParmVarDecl 0x56506d275598 <col:7> col:7 'A &&'
    |-CXXDestructorDecl 0x56506d275620 <col:7> col:7 implicit ~A 'void ()' inline default trivial noexcept-unevaluated 0x56506d275620
    |-CXXConstructorDecl 0x56506d2a4af0 <col:7> col:7 implicit constexpr A 'void (const A &)' inline default noexcept-unevaluated 0x56506d2a4af0
    | `-ParmVarDecl 0x56506d2a4c08 <col:7> col:7 'const A &'
    `-CXXConstructorDecl 0x56506d2a4c78 <col:7> col:7 implicit constexpr A 'void (A &&)' inline default noexcept-unevaluated 0x56506d2a4c78
      `-ParmVarDecl 0x56506d2a4d88 <col:7> col:7 'A &&'
    
    Layout: <CGRecordLayout
      LLVMType:%class.A = type <{ i32 (...)**, i32, [4 x i8] }>
      NonVirtualBaseLLVMType:%class.A.base = type <{ i32 (...)**, i32 }>
      IsZeroInitializable:1
      BitFields:[
    ]>
    
    *** Dumping IRgen Record Layout
    Record: CXXRecordDecl 0x56506d2757a8 <main.cpp:9:1, line:14:1> line:9:7 referenced class B definition
    |-DefinitionData polymorphic has_user_declared_ctor can_const_default_init
    | |-DefaultConstructor
    | |-CopyConstructor simple non_trivial has_const_param implicit_has_const_param
    | |-MoveConstructor exists simple non_trivial
    | |-CopyAssignment non_trivial has_const_param implicit_has_const_param
    | |-MoveAssignment exists simple non_trivial
    | `-Destructor simple irrelevant trivial
    |-public 'A'
    |-CXXRecordDecl 0x56506d275908 <col:1, col:7> col:7 implicit referenced class B
    |-AccessSpecDecl 0x56506d275998 <line:10:2, col:8> col:2 public
    |-CXXConstructorDecl 0x56506d275b68 <line:11:3, col:34> col:3 used B 'void (int, int)'
    | |-ParmVarDecl 0x56506d2759d8 <col:5, col:9> col:9 used a 'int'
    | |-ParmVarDecl 0x56506d275a58 <col:12, col:16> col:16 used b 'int'
    | |-CXXCtorInitializer 'A'
    | | `-CXXConstructExpr 0x56506d2a4e10 <col:21, col:24> 'A' 'void (int)'
    | |   `-ImplicitCastExpr 0x56506d2a4df8 <col:23> 'int' <LValueToRValue>
    | |     `-DeclRefExpr 0x56506d2a4aa0 <col:23> 'int' lvalue ParmVar 0x56506d2759d8 'a' 'int'
    | |-CXXCtorInitializer Field 0x56506d2a45d0 '_b' 'int'
    | | `-ImplicitCastExpr 0x56506d2a4ea8 <col:30> 'int' <LValueToRValue>
    | |   `-DeclRefExpr 0x56506d2a4e68 <col:30> 'int' lvalue ParmVar 0x56506d275a58 'b' 'int'
    | `-CompoundStmt 0x56506d2a4ef8 <col:33, col:34>
    |-AccessSpecDecl 0x56506d275c20 <line:12:2, col:9> col:2 private
    |-FieldDecl 0x56506d2a45d0 <line:13:3, col:7> col:7 _b 'int'
    |-CXXMethodDecl 0x56506d2a4678 <line:9:7> col:7 implicit operator= 'B &(const B &)' inline default noexcept-unevaluated 0x56506d2a4678
    | `-ParmVarDecl 0x56506d2a4788 <col:7> col:7 'const B &'
    |-CXXMethodDecl 0x56506d2a4828 <col:7> col:7 implicit operator= 'B &(B &&)' inline default noexcept-unevaluated 0x56506d2a4828
    | `-ParmVarDecl 0x56506d2a4938 <col:7> col:7 'B &&'
    |-CXXDestructorDecl 0x56506d2a49c0 <col:7> col:7 implicit ~B 'void ()' inline default trivial noexcept-unevaluated 0x56506d2a49c0
    |-CXXConstructorDecl 0x56506d2a5150 <col:7> col:7 implicit constexpr B 'void (const B &)' inline default noexcept-unevaluated 0x56506d2a5150
    | `-ParmVarDecl 0x56506d2a5268 <col:7> col:7 'const B &'
    `-CXXConstructorDecl 0x56506d2a52d8 <col:7> col:7 implicit constexpr B 'void (B &&)' inline default noexcept-unevaluated 0x56506d2a52d8
      `-ParmVarDecl 0x56506d2a53e8 <col:7> col:7 'B &&'
    
    Layout: <CGRecordLayout
      LLVMType:%class.B = type { %class.A.base, i32 }
      NonVirtualBaseLLVMType:%class.B = type { %class.A.base, i32 }
      IsZeroInitializable:1
      BitFields:[
    ]>
    

    读者想必应该能够自己寻找答案了

  4. 带有一个 virtual base class 的 class

    为了实现 virtual base class 的语义和功能,在 derived class 中必然需要进行一些额外的工作,这些工作是编译器来完成的

    如果存在任何 user_provided constructors,那么这些工作会被安插进入这些 user_provided constructors 中,如果没有 user_provided constructors,那么编译器会合成 non-trivial default constructor 来完成必要的工作(比如调用基类的 default constructor、设定虚机制所必须的相关信息之类)

    最后再举个例子吧:

    class A {
     private:
      int _a;
    };
    
    class B: public virtual A {
     private:
      int _b;
    };
    

    打印相关信息:

    *** Dumping AST Record Layout
             0 | class A
             0 |   int _a
               | [sizeof=4, dsize=4, align=4,
               |  nvsize=4, nvalign=4]
    
    *** Dumping AST Record Layout
             0 | class B
             0 |   (B vtable pointer)
             8 |   int _b
            12 |   class A (virtual base)
            12 |     int _a
               | [sizeof=16, dsize=16, align=8,
               |  nvsize=12, nvalign=8]
    
    *** Dumping IRgen Record Layout
    Record: CXXRecordDecl 0x557ad6558c50 <main.cpp:1:1, line:4:1> line:1:7 referenced class A definition
    |-DefinitionData pass_in_registers standard_layout trivially_copyable trivial literal
    | |-DefaultConstructor exists trivial
    | |-CopyConstructor simple trivial has_const_param implicit_has_const_param
    | |-MoveConstructor exists simple trivial
    | |-CopyAssignment trivial has_const_param implicit_has_const_param
    | |-MoveAssignment exists simple trivial
    | `-Destructor simple irrelevant trivial
    |-CXXRecordDecl 0x557ad6558d68 <col:1, col:7> col:7 implicit class A
    |-AccessSpecDecl 0x557ad6558df8 <line:2:2, col:9> col:2 private
    |-FieldDecl 0x557ad6558e38 <line:3:3, col:7> col:7 _a 'int'
    |-CXXMethodDecl 0x557ad6559368 <line:1:7> col:7 implicit constexpr operator= 'A &(const A &)' inline default trivial noexcept-unevaluated 0x557ad6559368
    | `-ParmVarDecl 0x557ad6559478 <col:7> col:7 'const A &'
    |-CXXMethodDecl 0x557ad6559518 <col:7> col:7 implicit constexpr operator= 'A &(A &&)' inline default trivial noexcept-unevaluated 0x557ad6559518
    | `-ParmVarDecl 0x557ad6559628 <col:7> col:7 'A &&'
    |-CXXDestructorDecl 0x557ad6559970 <col:7> col:7 implicit ~A 'void ()' inline default trivial noexcept-unevaluated 0x557ad6559970
    |-CXXConstructorDecl 0x557ad6586a08 <col:7> col:7 implicit used A 'void () noexcept' inline default trivial
    | `-CompoundStmt 0x557ad6587118 <col:7>
    |-CXXConstructorDecl 0x557ad6586c68 <col:7> col:7 implicit constexpr A 'void (const A &)' inline default trivial noexcept-unevaluated 0x557ad6586c68
    | `-ParmVarDecl 0x557ad6586d78 <col:7> col:7 'const A &'
    `-CXXConstructorDecl 0x557ad6586de8 <col:7> col:7 implicit constexpr A 'void (A &&)' inline default trivial noexcept-unevaluated 0x557ad6586de8
      `-ParmVarDecl 0x557ad6586ef8 <col:7> col:7 'A &&'
    
    Layout: <CGRecordLayout
      LLVMType:%class.A = type { i32 }
      NonVirtualBaseLLVMType:%class.A = type { i32 }
      IsZeroInitializable:1
      BitFields:[
    ]>
    
    *** Dumping IRgen Record Layout
    Record: CXXRecordDecl 0x557ad6558ea0 <main.cpp:6:1, line:9:1> line:6:7 referenced class B definition
    |-DefinitionData
    | |-DefaultConstructor exists non_trivial
    | |-CopyConstructor simple non_trivial has_const_param implicit_has_const_param
    | |-MoveConstructor exists simple non_trivial
    | |-CopyAssignment non_trivial has_const_param implicit_has_const_param
    | |-MoveAssignment exists simple non_trivial
    | `-Destructor simple irrelevant trivial
    |-virtual public 'A'
    |-CXXRecordDecl 0x557ad6559010 <col:1, col:7> col:7 implicit class B
    |-AccessSpecDecl 0x557ad65590a0 <line:7:2, col:9> col:2 private
    |-FieldDecl 0x557ad65590e0 <line:8:3, col:7> col:7 _b 'int'
    |-CXXMethodDecl 0x557ad6559188 <line:6:7> col:7 implicit operator= 'B &(const B &)' inline default noexcept-unevaluated 0x557ad6559188
    | `-ParmVarDecl 0x557ad6559298 <col:7> col:7 'const B &'
    |-CXXMethodDecl 0x557ad65596c8 <col:7> col:7 implicit operator= 'B &(B &&)' inline default noexcept-unevaluated 0x557ad65596c8
    | `-ParmVarDecl 0x557ad65597d8 <col:7> col:7 'B &&'
    |-CXXDestructorDecl 0x557ad6559860 <col:7> col:7 implicit ~B 'void ()' inline default trivial noexcept-unevaluated 0x557ad6559860
    |-CXXConstructorDecl 0x557ad6586910 <col:7> col:7 implicit used B 'void () noexcept' inline default
    | |-CXXCtorInitializer 'A'
    | | `-CXXConstructExpr 0x557ad6587128 <col:7> 'A' 'void () noexcept'
    | `-CompoundStmt 0x557ad6587190 <col:7>
    |-CXXConstructorDecl 0x557ad6586ae0 <col:7> col:7 implicit B 'void (const B &)' inline default noexcept-unevaluated 0x557ad6586ae0
    | `-ParmVarDecl 0x557ad6586bf8 <col:7> col:7 'const B &'
    `-CXXConstructorDecl 0x557ad6586f68 <col:7> col:7 implicit B 'void (B &&)' inline default noexcept-unevaluated 0x557ad6586f68
      `-ParmVarDecl 0x557ad6587078 <col:7> col:7 'B &&'
    
    Layout: <CGRecordLayout
      LLVMType:%class.B = type <{ i32 (...)**, i32, %class.A }>
      NonVirtualBaseLLVMType:%class.B.base = type <{ i32 (...)**, i32 }>
      IsZeroInitializable:1
      BitFields:[
    ]>
    
    Record: CXXRecordDecl 0x557ad6558ea0 <main.cpp:6:1, line:9:1> line:6:7 referenced class B definition
    |-DefinitionData
    | |-DefaultConstructor exists non_trivial
    

    可以看到 class B 存在 default constructor 且是 non-trivial 的

总结

  1. 如果没有任何 user_provided constructor,那么编译器会始终生成一个 default constructor(反之,如果存在任何 user_provided constrcutor,那么除非强制生成,否则编译器是不会生成 defualt construcotor 的)
  2. 编译器生成的 default constructor 分 trivial 和 non-trivial 两种

C++新手一般有两个误区:

  • 任何 class 如果没有定义 default constructor,编译器就会自动合成一个
  • 编译器合成出来的 default constructor 会为成员变量设定默认值

PS:default constructor 的大概知识就到此结束啦,本文也只是走马观花的介绍了 default constructor 的相关知识,更加详细的还是请移步至 cppreference 查阅相关文档

posted @ 2019-10-16 22:45  cookcocck  阅读(767)  评论(0编辑  收藏  举报