我有以下代码
string three()
{
return "three";
}
void mutate(string& ref)
{
}
int main()
{
mutate(three());
return 0;
}
您可以看到我正在将three()传递给mutate方法。这段代码编译得很好。我的理解是,不能将临时对象分配给非常量引用。如果是,这个程序是如何编译的?
有什么想法吗?
编辑:
编译器尝试:VS 2008 和 VS2010 Beta
我有以下代码
string three()
{
return "three";
}
void mutate(string& ref)
{
}
int main()
{
mutate(three());
return 0;
}
您可以看到我正在将three()传递给mutate方法。这段代码编译得很好。我的理解是,不能将临时对象分配给非常量引用。如果是,这个程序是如何编译的?
有什么想法吗?
编辑:
编译器尝试:VS 2008 和 VS2010 Beta
它曾经在 VC6 编译器中编译,所以我想保持向后兼容性 VS2008 支持这种非标准扩展。尝试使用/Za(禁用语言扩展)标志,然后您应该会收到错误消息。
它是 VC++ 的邪恶扩展。如果您使用 /W4 进行 oompile,那么编译器会警告您。我猜你正在阅读Rvalue References: C++0x Features in VC10, Part 2。这篇文章也提到了这个问题。
这是一个 Microsoft 扩展,用于模仿许多其他 Microsoft 编译器的行为。如果启用 W4 警告,您将看到警告。
它不能编译,至少使用 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.
也许是因为您没有做任何事情,所以呼叫被优化掉了。