基类在一个派生类的复制构造函数(C ++)的初始化列表
让我们举个例子:
class Base {
Base (const Base & copyFrom) { globalRegister (* this); }
}
class Derived {
Derived (const Derived & copyFrom) : Base (copyFrom) {}
}
我已经阅读过建议,将Base的拷贝构造函数包含在Derived的初始化列表中,以便拷贝Base的属性)。
I've read suggestions to include the Base's copy constructor on the initialisation list of Derived in order to copy over the Base's properties (as in the example).
但是,我有Base的复制构造函数将自身(* this)传递给其他对象(要注册到该对象)。这是一种情况,我实际上必须使用(隐式或显式)在Derived的复制构造函数的初始化列表的基本(默认)构造函数,并且只有在Derived的复制构造函数的主体中调用Base的复制构造函数,当实际上有一个对象可以通过Base的拷贝构造函数附加? Else - 是(* this)有效对象?
However, I have the Base's copy constructor passing itself (* this) to other object (to be registered with that object). Would that be a case where I actually must use (implicitly or explicitly) Base's (default) constructor on the initialisation list of Derived's copy constructor, and call the Base's copy constructor only in the body of Derived's copy constructor, when there is actually an object that can be attached by Base's copy constructor? Else - is (* this) a valid object?
实际上必须在Derived的拷贝构造函数的初始化列表中使用(隐式或显式地)Base(默认)构造函数,并且只有在Derived的拷贝构造函数的主体中才调用Base的拷贝构造函数,当实际上有一个可以通过Base拷贝构造函数?
Would that be a case where I actually must use (implicitly or explicitly) Base's (default) constructor on the initialisation list of Derived's copy constructor, and call the Base's copy constructor only in the body of Derived's copy constructor, when there is actually an object that can be attached by Base's copy constructor?
为什么你想这样做?
(哦,只有从它的初始化列表中。)
Why on earth would you want to do that?
(Oh, and you can not call a base class' copy constructor from a derived class' constructor's body. Only from its initialization list.)
Else - 从构造函数的 (* this)一个有效的对象?
Else - is (* this) a valid object?
基本初始化列表完成后,所有base的成员完全建成。然而,类本身只有在它的构造函数完成时才被完全构造。
更重要的是,派生类的构造函数还没有开始,所以对象不是派生类对象。
The moment the base's initialization list has completed, all of base's members (and base classes) are fully constructed. The class itself, however, is only fully constructed when its constructor has finished.
More importantly, the derived class' constructor hasn't even started yet, so the object is not a derived class' object yet.
因此,无论注册函数如何操作,都必须考虑对象的动态类型是 base 并且它的构造函数还没有完成。 (为了安全起见,它所能做的只是将对象的地址存储在某个地方。)
So whatever that registering function does, it has to take into account that the object's dynamic type is base
and that its constructor hasn't finished yet. (To be safe, all it can do is to store the object's address somewhere.)