12

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
但情况相反。
请说明原因。

4

1 回答 1

3

我已经用 MS VS 2010 试过这个,它给了我输出,在编译过程中也给出了警告:

警告 C4413: 'bar::ref' : 引用成员被初始化为一个临时的,在构造函数退出后不会持续存在

foo c'tor
bar c'tor
foo d'tor
Press any key to continue . . .

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.

于 2011-01-18T09:32:05.307 回答