C++03 中的第 12.2.5 节说“临时绑定到构造函数的 ctor-initializer (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
现在根据标准,由 bar 的 c'tor 的 c'tor init-list 中的 foo() 临时生成的临时文件将在 bar 的 c'tor 之后被销毁,因此foo d'tor
应该在之后打印,bar c'tor
但情况相反。
请说明原因。