Passing an anonymous variable by reference

蓝咒 提交于 2019-12-03 14:16:06

If your compiler allows this, then it's not a standard compatible C++ compiler. You can not bind a temporary rvalue to a non-const lvalue reference. It's the rule. Both clang and gcc don't compile that code for func2(STRUCT(65));.

Instead you have alternatives:

void func1(int&& i){}

void func1(const int& i){}

Legacy from C++03: A (lvalue) reference to a non-const type (int &i) supposed to able to change the parameter then passing a temporary object such as 56 is not logical because it not changeable. A reference to a const type (const int &i) supposed to just observe the value as read-only, then passing a temporary value such as 52 is legal.

In C++11 you can reference to a non-const temporary object by &&.

It seems that you are using MS VC++ compiler that has such bug.:) You have to bind temporary object with const reference. For example you may write

const int &ri = 10;

but you may not write

int &ri = 10;

The same is valid for user-defined types.

const STRUCT &rs = STRUCT( 10 );

STRUCT &rs = STRUCT( 10 ); // the compiler shall issue an error.

In c++,an anonymous temporary object is always a right-value.To accept an right-value as argument,you can:

1).void foo1(TYPE); //passing by value
2).void foo2(const TYPE &); //passing by const reference
3).void foo3(TYPE &&); //in c++11,passing by right-value reference

Your "func3" and "func4" accept an argument that passed by value,it's ok.
However,"func1" and "func2" can only accept an argument that passed by a left-value reference.So it's wrong to pass an anonymous parameter.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!