将临时绑定到左值引用

问题描述 投票:0回答:5

我有以下代码

string three()
{
    return "three";
}

void mutate(string& ref)
{
}

int main()
{
    mutate(three()); 
    return 0;
}

您可以看到我正在将 Three() 传递给 mutate 方法。这段代码编译得很好。我的理解是,临时变量不能分配给非常量引用。如果是,这个程序是如何编译的?

有什么想法吗?

编辑:

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

c++ compiler-construction lvalue rvalue
5个回答
8
投票

它曾经在VC6编译器中编译,所以我猜VS2008为了保持向后兼容性而支持这个非标准扩展。尝试使用 /Za(禁用语言扩展)标志,然后您应该会收到错误。


4
投票

它是VC++的邪恶扩展。如果您使用 /W4 进行编译,那么编译器会警告您。我猜您正在阅读 Rvalue References: C++0x Features in VC10, Part 2。这篇文章也提到了这个问题。


3
投票

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


1
投票

不能编译,至少使用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' 行。)

所以,你的编译器似乎没有应有的那么严格。


0
投票

我想这取决于编译器。 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.

也许因为你没有做任何事情,所以调用被优化掉了。

© www.soinside.com 2019 - 2024. All rights reserved.