C++ 将临时绑定到左值引用

C++ 将临时绑定到左值引用,c++,compiler-construction,lvalue,rvalue,C++,Compiler Construction,Lvalue,Rvalue,我有以下代码 string three() { return "three"; } void mutate(string& ref) { } int main() { mutate(three()); return 0; } 您可以看到,我正在将3()传递给mutate方法。这段代码编译得很好。我的理解是,临时变量不能分配给非常量引用。如果是,该程序是如何编译的 有什么想法吗 编辑: 编译器尝试过:VS 2008和VS2010 Beta版它无法编译,至少使

我有以下代码

string three()
{
    return "three";
}

void mutate(string& ref)
{
}

int main()
{
    mutate(three()); 
    return 0;
}
您可以看到,我正在将3()传递给mutate方法。这段代码编译得很好。我的理解是,临时变量不能分配给非常量引用。如果是,该程序是如何编译的

有什么想法吗

编辑:

编译器尝试过:VS 2008和VS2010 Beta版

它无法编译,至少使用了g++4:

foo.cpp: In function ‘int main()’:
foo.cpp:16: error: invalid initialization of non-const reference of type ‘std::string&’ from a temporary of type ‘std::string’
foo.cpp:10: error: in passing argument 1 of ‘void mutate(std::string&)’
(行号减少了3或4,因为我必须添加#include和‘using’行。)


因此,您的编译器似乎没有达到应有的严格程度。

我想这取决于编译器。g++4.1.2给了我这个

In function 'int main()':
Line 15: error: invalid initialization of non-const reference of type 'std::string&' from a temporary of type 'std::string'
compilation terminated due to -Wfatal-errors.

可能是因为您没有做任何事情,所以调用被优化掉了。

它过去是在VC6编译器中编译的,所以我想为了保持向后兼容性,VS2008支持这种非标准扩展。尝试使用(禁用语言扩展)标志,您应该会得到一个错误。

这是一个Microsoft扩展,模仿许多其他Microsoft编译器的行为。如果启用W4警告,您将看到警告。

这是VC++的邪恶扩展。如果您使用/W4进行编译,编译器将警告您。我猜你在看报纸。本文还提到了问题。

编辑后的文章和添加的编译器。我尝试使用GCC,它更接近C++标准。不幸的是,我没有GCC。@科莫:在我修改了代码中的“缺失”和“代码> STD < /Cord>前缀之后,”()):<代码>引用非const的初始值必须是LValue/Cuth>。VC之所以接受这一点,是因为VC破产了。(他们称之为“功能”,但实际上这是一个bug。)我尝试在mutate()方法中使用ref参数,但它仍然可以编译。我刚刚在VC++中尝试过,它可以编译并工作,除非您在项目属性中禁用扩展。当你得到这个:1>main.cpp 1>d:\all\projects\laptop\2\asd\asd\main.cpp(16):错误C2664:“mutate”:无法将参数1从'std::string'转换为'std::string&'1>非常量引用只能绑定到左值。指定
/Za
选项可能会导致包含
windows.h
或其他特定于windows的标头时出现问题。使用警告级别为4是我使用的更好的选项