Naturally, this won't compile:
int &z = 3; // error: invalid initialization of non-const reference ....
and this will compile:
const int &z = 3; // OK
Now, consider:
const int y = 3;
int && yrr = y; // const error (as you would expect)
int && yrr = move(y); // const error (as you would expect)
But these next lines do compile for me. I think it shouldn't.
int && w = 3;
int && yrr = move(3);
void bar(int && x) {x = 10;}
bar(3);
Wouldn't those last two lines allow the literal 3 to be modified? What is the difference between 3
and a const int? And finally, Is there any danger with 'modifying' literals?
(g++-4.6 (GCC) 4.6.2 with -std=gnu++0x -Wall -Wextra
)
Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well.
What are numeric literals? Numeric literals are used to represent numbers in a python program.In python we have different types of numeric literals such as integers, floating point numbers and complex numbers. Integers in python are numbers with no fractional component.
A literal (or literal data) is data that appears directly in the source code, like the number 5, the character A, and the text “Hello, World.” A value is an immutable, typed storage unit. A value can be assigned data when it is defined, but can never be reassigned. A variable is a mutable, typed storage unit.
Literals in Python is defined as the raw data assigned to variables or constants while programming. We mainly have five types of literals which includes string literals, numeric literals, boolean literals, literal collections and a special literal None.
The rvalue reference to the literal 3
:
int && w = 3;
is actually bound to a temporary that is the result of evaluating the expression 3
. It's not bound to some Platonic literal 3.
(all the following standards references are from the March 2011 draft, n3242)
3.10/1 "Lvalues and rvalues"
The value of a literal such as 12, 7.3e5, or true is also a prvalue
Then 8.5.3 "References" gives the rules for how a reference is bound falls through to the last case, which says:
Otherwise, a temporary of type “cv1 T1” is created and initialized from the initializer expression using the rules for a non-reference copy-initialization (8.5). The reference is then bound to the temporary.
and gives as one example something very close to what's in your question:
double&& rrd = 2; // rrd refers to temporary with value 2.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With