c++ - 为什么临时对象的引用在这里有效?

标签 c++ visual-c++

<分区>

Possible Duplicate:
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+函数的第一个参数是一个引用。为什么临时对象的引用在这里有效,或者我错过了什么?

P.S:VC++6.0编译,运行结果如下。 enter image description here

最佳答案

临时对象持续到创建它们的完整表达式的末尾 - 粗略地说,直到 ; 在该行的末尾。在此之前,对它们的引用是有效的。

但是,像您那样将其绑定(bind)到非const 引用是无效的。编译的唯一原因是因为您的编译器已有 15 年以上的历史,并且从那时起该语言经历了两次重大变化。我建议您升级到本世纪的编译器之一。

关于c++ - 为什么临时对象的引用在这里有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10088741/

相关文章:

c++ - 将 "getline"与数组一起使用

c++ - 查找与一组规则匹配的所有排列

c++ - 在初始化列表中使用后递增运算符

python - Visual Studio 更新到 15.0 后出现扭曲安装问题

c++ - 为结构字段赋值时程序崩溃

c++ - 指针在删除它并在 C++ 中再次分配新内存后是否获得相同的内存地址?

c++ - 互斥锁会停止 mingw 中的程序,但不会在 Linux 上停止

C++ WIN32 : where to put code that executes as program is running

C++ 创建通用模板函数特化

c++ - 我的代码正确地旋转了一张 bmp 图片,但前提是像素数是 4 的倍数......任何人都可以看出问题所在吗?