问题描述
可以像下面的示例一样将未初始化的对象传递给父类
It is possible to pass uninitialized object to a parent class like in the following example
class C
{
public:
C(int i):
m_i(i)
{};
int m_i;
}
class T
{
public:
T(C & c):
m_c(c)
{
};
C & m_c;
};
class ST : public T
{
public:
ST():
T(m_ci),
m_ci(999)
{
};
C m_ci;
};
在 class T
构造函数中, c
是对未初始化对象的引用。如果 Class T
在构造过程中使用 c
对象,则可能会导致错误。但是由于不是这样,因此可以编译并正常运行。我的问题是-它会破坏某种范例还是好的设计指令?如果是这样,有什么替代方法,因为我发现在子类中分配父级所需的对象很有用。
In class T
constructor, c
is a reference to uninitialized object. If class T
were using c
object during construction, this would possibly lead to an error. But since it's not, this compiles and works fine. My question is - does it brake some kind of paradigm or good design directives? If so, what are the alternatives, because I found it useful to allocate an object required by parent in a subclass.
在旁注中,我想知道为什么不可能更改初始化顺序,以便在某些成员初始化之后调用基类构造函数。
On a side note, I wonder why it's not possible to change initialization order, so that base class constructor would be called after initialization of some members.
推荐答案
您可以,但是您得到不确定的行为。
You can, but you get undefined behavior.
在Boost的实用程序中,您会找到由。基本上,您可以在私人成员的位置建立私人基地。此基础首先被初始化,您可以将其用于其他基础:
In Boost's utilities, you'll find the base-from-member idiom created by R. Samuel Klatchko. Basically, you make a private base in the place of the private member. This base gets initialized first, and you can use it for other bases:
// ...
class C_base
{
public:
C_base(int i) :
m_ci(i)
{}
C m_ci;
};
class ST :
private C_base
public T
{
public:
ST() :
C_base(999),
T(m_ci),
{
};
};
Boost的实用程序消除了重复的代码。
Boost's utility eliminates repeated code.
这篇关于对未初始化对象iniside构造函数的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!