将临时绑定到 c'tor 初始值设定项列表中的 const 引用
C++03 中的第 12.2.5 节说“临时绑定到 a 中的引用成员 构造函数的构造函数初始化程序 (12.6.2) 持续存在,直到构造函数退出”
所以我尝试了以下程序
#include<iostream>
using namespace std;
struct foo
{
foo()
{
cout<<"foo c'tor"<<endl;
}
~foo()
{
cout<<"foo d'tor"<<endl;
}
};
struct bar
{
const foo &ref;
bar():ref(foo())
{
cout<<"bar c'tor"<<endl;
}
};
int main()
{
bar obj;
}
我得到的输出是:
foo c'tor
foo d'tor
bar c'tor
现在根据标准,由 foo() 在 bar 的 c'tor 的 c'tor init-list 中生成的临时文件将在 bar 的 c'tor 之后被销毁,所以 foo d'tor
应在 bar c'tor
之后打印 但事实恰恰相反。
请解释原因。
Section 12.2.5 in C++03 says "A temporary bound to a reference member in a
constructor’s ctor-initializer (12.6.2) persists until the constructor exits"
So I tried following program
#include<iostream>
using namespace std;
struct foo
{
foo()
{
cout<<"foo c'tor"<<endl;
}
~foo()
{
cout<<"foo d'tor"<<endl;
}
};
struct bar
{
const foo &ref;
bar():ref(foo())
{
cout<<"bar c'tor"<<endl;
}
};
int main()
{
bar obj;
}
The output I get is :
foo c'tor
foo d'tor
bar c'tor
Now according to standard, temporary generated by foo() in c'tor init-list of bar's c'tor will be destroyed after bar's c'tor so foo d'tor
should be printed after bar c'tor
but it's other way around.
Please explain the reason.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我已经用 MS VS 2010 尝试过这个,它给我的输出在编译过程中也给出了警告:
警告 C4413: 'bar::ref' : 引用成员被初始化为一个临时的,在构造函数退出后不会持续存在
看来 MS VS 2010 正确实现了规范。我同意这是 g++ 的一个错误。
编辑: ref 应该在构造函数的初始化列表中初始化。
I have tried this with MS VS 2010, and it gives me the output also gives warning during compile:
warning C4413: 'bar::ref' : reference member is initialized to a temporary that doesn't persist after the constructor exits
It seems that MS VS 2010 implements specification correctly. I agree that it is a bug for g++.
EDIT: ref should be initialized in constructor`s initialize list.