Initializing reference variables with the conditional operator

十年热恋 提交于 2019-12-10 03:39:56

问题


The following C++ is invalid because reference variables require initializers:

int& a; // illegal
if (isfive) {
  a = 5;
} else {
  a = 4;
}

However, MSVC seems to think this is okay:

int& a = isfive ? 5 : 4;

This implies to me that MSVC is actually treating the conditional operator like a single expression and not expanding it into an if-else statement.

Is it always valid C++ to initialize a reference using the conditional operator?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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




回答5:


it is not OK

int& a = isfive ? 5 : 4;

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




回答6:


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



来源:https://stackoverflow.com/questions/9200087/initializing-reference-variables-with-the-conditional-operator

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