[英]Binding temporary to a lvalue reference
I have the following code我有以下代码
string three()
{
return "three";
}
void mutate(string& ref)
{
}
int main()
{
mutate(three());
return 0;
}
You can see I am passing three() to mutate method.你可以看到我正在传递三个()到mutate方法。 This code compiles well.这段代码编译得很好。 My understanding is, temporaries can't be assigned to non-const references.我的理解是,不能将临时变量分配给非常量引用。 If yes, how this program is compiling?如果是,这个程序是如何编译的?
Any thoughts?有什么想法吗?
Edit:编辑:
Compilers tried : VS 2008 and VS2010 Beta编译器尝试过:VS 2008 和 VS2010 Beta
It is VC++'s evil extension.它是 VC++ 的邪恶扩展。 If You oompile with /W4 then the compiler will warn you.如果您使用 /W4 编译,那么编译器会警告您。 I guess you are reading the Rvalue References: C++0x Features in VC10, Part 2 .我猜您正在阅读Rvalue References: C++0x Features in VC10, Part 2 。 This article had also mentioned that issue.这篇文章也提到了这个问题。
This is a Microsoft Extension, to mimic the behavoir of many other microsoft compilers.这是一个微软扩展,模仿许多其他微软编译器的行为。 If you enable W4 warnings, you will see the warning.如果启用 W4 警告,您将看到警告。
It doesn't compile, with g++ 4 at least:它无法编译,至少使用 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&)’
(The line numbers are off by 3 or 4, because I had to add the #include and 'using' lines.) (行号减少了 3 或 4,因为我必须添加 #include 和 'using' 行。)
So, your compiler appears to not be as strict as it should be.因此,您的编译器似乎没有应有的严格。
I guess it depends on the compiler.我想这取决于编译器。 g++ 4.1.2 gives me this. 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.
Maybe because you're not doing anything the call is optimized away.也许是因为您没有做任何事情,所以呼叫被优化掉了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.