Initializing reference variables with the conditional operator

感情迁移 提交于 2019-12-05 06:32:14

MSVC has a non-standard "extension". What it means is that it allows broken code. There's a good reason this is prohibited.

Note also that

int& a = 5;

is not legal in Standard C++ either.

In general, though, it is legal to initialize a const reference with any expression which can be converted to the right type (including use of the conditional operator). And it is legal to initialize a non-const reference with an lvalue of the right type, which the conditional operator yields under certain conditions.

The ternary operator does not expand to an if-else construct (not according to the language, the implementation might generate equivalent binaries, but at the language level they are different). So the following code is valid:

int four = 4, five = 5;
int& r = condition? four : five;

The original example in the question depends on a Microsoft extension that (incorrectly) allows binding a non-const reference to an rvalue expression.

The code you posted does not compile with VC++ 2010:

Error 1 error C2440: 'initializing' : cannot convert from 'int' to 'int &'

Changing the line to:

const int& a = isfive ? 5 : 4; 

makes it compile.

The conditional operator is an expression, not a statement. It is perfectly fine to initialise a reference like that. It's a little like initialising a reference by calling a function.

Note that your reference needs to be const if you bind it to temporaries (a rule which MSVC++ stupidly ignores).

it is not OK

int& a = isfive ? 5 : 4;

unless you declare the reference "a" as a const.

It is operator, part of the expression, not a statement. And you can't leave reference uninitialized even for a short while ;-)

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