开发者

can we assign a integer value to a reference variable?

It is not possible to assign an integer value to a reference variable directly, say like:

int &x=10; //not possible

Is there any other way we c开发者_C百科an modify this statement to make it possible?

But not like this:

int a=10;int &x=a;

This works fine. But I want some other way or modify a little bit my expression and make it work!


The reference as the name says has to reference to something. How do you want to assign a value to it if it doesn't reference anything?


The reason it doesn't work is because 10 is of the type "const int". You can turn that into a reference, but you can't make it non-const without violating some logic at the least.

const int &a = 10;

that'll work.

int &b = const_cast<int &>(static_cast<const int &>(10));

will also compile, but you can't modify b (as that would imply modifying the actual "10" value).


The crux is that 10 is a constant – somewhat obviously: you cannot change its value. But if you try to assign it to an int reference, this would mean that the value were modifiable: an int& is a modifiable value.

To make your statement work, you can use a const reference:

int const& x = 10;

But as “cnicutar” has mentioned in a comment, this is pretty useless; just assign the 10 to a plain int.


You can't bind a reference-to-nonconst to anything immutable.

  • The standard permits storing compile time constants in ROM (btw, attempting to modify const_cast<>ed compile time constants yields undefined behaviour)
  • This would basically strip of the const, even if the const is invisible, therefore subverting the whole const-correctness-thing

However, you can bind a reference-to-const to nearly everything, including temporaries:

  • GotW: A candidate for the most important const

Consider this a "feature".


References refer to objects (perhaps temporary objects), not to values. If you want to store a value somewhere, assign it to an object, not to a reference.

As a special case, const int &a = 10; initializes the reference a to refer to a temporary object with the value 10, and it extends the lifetime of that temporary to the end of the scope of a (12.2/5). That's pretty useless with an integer literal, but occasionally useful with objects of class type. Still, this does not assign an integer value to a reference. It creates a temporary, and binds a reference to the temporary.


in the C++0x, you can use int&& (rvalue references ), but this can be used as function parameter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜