【问题标题】:inheritance and sequence of initialization继承和初始化序列
【发布时间】:2016-09-06 22:11:45
【问题描述】:

考虑

 class A
   {
   };

 class B
   {
     B(A * in);
   };

 class C : public A
  {
    B b;
   public:
   C():b(this){}
  };

C 中的构造函数安全吗? A 的成员是否已经可用(并已构建)?

【问题讨论】:

  • 定义“安全”..

标签: c++ inheritance constructor initialization


【解决方案1】:

是的。所有 Base 类都是在构造函数的其余部分执行之前构造的。

例如,来自 Stroustrup C++ 2011 书:

17.2.3 Base and Member Destructors
Constructors and destructors interact correctly with class hierarchies (§3.2.4, Chapter 20). A constructor
builds a class object ‘‘from the bottom up’’:
[1] first, the constructor invokes its base class constructors,
[2] then, it invokes the member constructors, and
[3] finally, it executes its own body.
A destructor ‘‘tears down’’ an object in the reverse order:
[1] first, the destructor executes its own body,
[2] then, it invokes its member destructors, and
[3] finally, it inv okes its base class destructors.

【讨论】:

  • 除非B的构造函数尝试在in上调用virtual函数。
猜你喜欢
  • 1970-01-01
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多