Binding temporary to a lvalue reference

2019-01-25 10:15发布

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. 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

5条回答
我想做一个坏孩纸
2楼-- · 2019-01-25 10:53

I guess it depends on the compiler. g++ 4.1.2 gives me this.

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.

查看更多
劳资没心,怎么记你
3楼-- · 2019-01-25 10:56

It used to compile in VC6 compiler, so I guess to maintain backward comptibility VS2008 is supporting this non-standard extension. Try with /Za (disable language extension) flag, you should get an error then.

查看更多
聊天终结者
4楼-- · 2019-01-25 11:08

It is VC++'s evil extension. If You oompile with /W4 then the compiler will warn you. I guess you are reading the Rvalue References: C++0x Features in VC10, Part 2. This article had also mentioned that issue.

查看更多
别忘想泡老子
5楼-- · 2019-01-25 11:08

This is a Microsoft Extension, to mimic the behavoir of many other microsoft compilers. If you enable W4 warnings, you will see the warning.

查看更多
Anthone
6楼-- · 2019-01-25 11:09

It doesn't compile, with g++ 4 at least:

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.)

So, your compiler appears to not be as strict as it should be.

查看更多
登录 后发表回答