在c'tor初始化器列表中绑定临时到const引用 [英] Binding temporary to const reference in c'tor initializer list

查看:198
本文介绍了在c'tor初始化器列表中绑定临时到const引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 03中的第12.2.5节说
构造函数的ctor-initializer(12.6.2)中临时绑定到引用成员,直到构造函数退出
< br>
所以我试过下面的程序

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;
}    

我得到的输出是:

foo c'tor
foo d'tor
bar c'tor

现在根据标准,bar的c'tor的c'tor init-list中的foo()生成的临时变量将在bar的c'tor之后被销毁,因此 bar c'tor

之后,应打印 b $ b请解释原因。

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.

推荐答案

我已经尝试过MS VS 2010,在编译期间警告:

I have tried this with MS VS 2010, and it gives me the output also gives warning during compile:

警告C4413:'bar :: ref':引用成员被初始化为一个临时, strong>

warning C4413: 'bar::ref' : reference member is initialized to a temporary that doesn't persist after the constructor exits

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

似乎MS VS 2010正确地实现了规范。我同意这是g ++的错误。

It seems that MS VS 2010 implements specification correctly. I agree that it is a bug for g++.

编辑:ref应该在构造函数的初始化列表中初始化。

ref should be initialized in constructor`s initialize list.

这篇关于在c'tor初始化器列表中绑定临时到const引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆