C++0x 中的继承构造函数
假设我有以下代码,我们期望成为下一个 C++ 标准:
int f(int x)
{
std::cout << x;
return x * x;
}
struct A
{
A(int x) : m_x(x) {}
int m_x;
};
struct B : A
{
using A::A;
B() : m_y(f(m_x)) {}
int m_y;
};
int main()
{
B(5);
}
这会调用 B 的默认构造函数并打印出 5 并设置 m_y = 25 吗?或者 B 的默认构造函数不会运行,并且 m_y 未初始化?
如果是后者,不调用 B 默认构造函数的理由是什么?很明显,A(int) B 只继承了 A 的初始化,而使 B 处于不确定状态。为什么 C++ 会选择未定义的行为而不是简单地调用 B() 的默认构造函数?它在很大程度上违背了继承构造函数功能的目的。
编辑:
也许应该允许这样做:
using A::A : m_y(...) { std::cout << "constructing..." << std::endl; ...; }
Lets say I have the following code in what we expect to become the next C++ standard:
int f(int x)
{
std::cout << x;
return x * x;
}
struct A
{
A(int x) : m_x(x) {}
int m_x;
};
struct B : A
{
using A::A;
B() : m_y(f(m_x)) {}
int m_y;
};
int main()
{
B(5);
}
Would this call the default constructor of B and print out 5 and set m_y = 25? Or will the default constructor of B not run, and leave m_y uninitialized?
And if the latter, what is the rationale behind not calling the B default constructor? It is quite clear that the A(int) B inherits only initialises A, and leaves B in an indeterminate state. Why would C++ choose undefined behaviour over simply calling the default constructor of B()? It largely defeats the purpose of the inheriting constructors feature.
Edit:
Perhaps this should be allowed:
using A::A : m_y(...) { std::cout << "constructing..." << std::endl; ...; }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
using A::A;
在派生类中隐式声明B(int)
。就是这样。程序的其余部分不应按您的预期工作。因为您使用
B(5)
调用B(int)
,导致m_y
未初始化。请参阅 Bjarne Stroustrup 网站上的示例:
http://www2.research .att.com/~bs/C++0xFAQ.html#inheriting
来自同一链接的另一个示例:
using A::A;
implicitly declaresB(int)
in the derived class. That is it.The rest of your program should not work as you expect. Because you're invoking
B(int)
withB(5)
, and that leavesm_y
uninitialized.See this example from Bjarne Stroustrup's site:
http://www2.research.att.com/~bs/C++0xFAQ.html#inheriting
Another example from the same link: