本文介绍了在c'tor初始化器列表中绑定临时到const引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 C ++ 03中的第12.2.5节说在构造函数的ctor-initializer(12.6.2)中临时绑定到引用成员,直到构造函数退出 所以我试过下面的程序Section 12.2.5 in C++03 says "A temporary bound to a reference member in aconstructor’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'torfoo d'torbar 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'torbut 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 exitsfoo c'torbar c'torfoo d'torPress 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引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-20 17:37