【发布时间】:2012-04-10 12:23:12
【问题描述】:
可能重复:
Is it a bug that Microsoft VS C++ compiler can Initialize a reference from a temporary object
#include <iostream>
#include <string>
using namespace std;
class test
{
public:
string a;
public:
test(string b){a=b;}
friend string operator+(test);
};
string operator+(string &c,test a)
{
c=c+a.a;
return c;
}
void main()
{
test d("the ");
test e("world!");
string s="Hello ";
s=s+d+e;
cout<<s<<endl;
}
倒数第二行s=s+d+e;在第一个重载的operator+之后返回了一个临时对象,第二个重载的operator+居然起作用了!但是operator+函数的第一个参数是参考。为什么临时对象的引用在这里有效,或者我错过了什么?
P.S:VC++6.0编译,运行结果如下
【问题讨论】:
-
在语言标准化之前,它是 MS 编译器支持的“扩展”。 VS2010 对此发出警告。
-
抱歉,我没有看到任何临时对象。临时对象在哪里?
-
@MrLister:仔细看——这里使用的
operator+按值返回——所以它确实是一个临时的。 -
但它是一个真实的字符串,一个真实的对象。仅当您在函数中创建对象然后返回对它的引用时,才会存在临时对象引用的问题,因为该对象在函数结束时调用其析构函数。这里情况不同!你返回 c 的值!
-
@MrLister:
operator+返回的值是一个临时对象,直到完整表达式结束才有效。您是正确的,它不是对函数返回时销毁的自动对象的引用;但这不是问题所在。
标签: c++ visual-c++