I am reading about references in C++. It says that int& a = 5 gives compile time error.
In Thinking in C++ - Bruce Eckel, author says that compiler must first allocate the storage for an int and produce the address to bind to the reference. The storage must be const because changing it would make no sense.
I am confused at this point. I am not able to understand the logic behind it. Why can't be change the content in the storage? I understand that it's invalid as per C++ rules, but why?
"The storage must be const because changing it would make no sense."
If you want a be a reference to a const value, you must declare it as const, because a is referencing to a temporary constant value, and changing it is not possible.
const int &a = 123;
a = 1000; // `a` is referencing to temporary 123, it is not possible to change it
// We can not change 123 to 1000
// Infact, we can change a variable which its value is 123 to 1000
// Here `a` is not a normal variable, it's a reference to a const
// Generally, `int &a` can not bind to a temporary object
For non-const bindings:
int x = 1;
int &a = x;
a is a reference to a lvalue. Simple speaking, it's an alias name for another variable, so on the right hand you should give a variable. The reference a can not change and bind to another variable after it's first binding;
In C++11, you can reference to temporary objects/values by rvalue references:
int &&a = 123;
int& a = 5;
In order for the above code to work, int& needs to bind to a temporary object of type int created out of the expression 5. But binding int& to a temporay didn't appeal to Bjarne Stroustrup — and he gave an example, similar to the following, to illustrate his point:
void f(int &i) { ++i; }
float x = 10.0;
f(x);
std::cout << x <<< std::endl;
What will the std::cout print1? Looks like it will print 11.
It feels, ++i is changing the argument x, but it doesn't. This is one reason why the creator of C++ didn't permit temporaries to bind to non-const reference.
However, you can do this:
int const & i = 10;
int const & j = x; //x is float
And since C++11, you can do this:
int && i = 10;
int && i = x; //x is float
Hope that helps.
1. assuming int& can bind to the temporary created out of x.
What you can do is
int b=5;
int &a=b;
or
const int& a = 5;
Related
eg:
//The standard method
int x=10;
int &y=x;
I tried
int &y;
y=x;
It didn't work, I am looking for another way to run it.
There are 2 types of reference:
rvalue - refer to persistent objects whose value you want to change
lvalue - refer to temporary objects whose value you want to change
lvalue Example:
int num = 1;
int& r1 {num};
int& r2; // error: need initialization
int& r2 = num;
int* p = #
int& r3 = *p;
rvalue Example:
int&& rr1{ int() }; // temporary
int&& rr2{ 2 }; // temporary
You can't declare a reference without initialising it. Maybe what you want is a pointer.
I understand the reference variable concept. It's an alias to the other variable.
int varA = 100;
int &varB = varA;
Here varB is a referring to varA, both pointing to same memory location. Changes to one variable reflect in the other.
Question:
a) int &c = 100;
What is the meaning of the above statement, and how does it differ from the following?
b) int c = 100;
Is there any scenario where we need to use 1(a) rather than 1(b)?
All are correct, except this:
int &c = 100; //error
It will give compilation error both in C++03, and C++11. It is because it attempts to bind non-const reference to a temporary object (created out of 100) which is disallowed.
In C++11, you could do this, however:
int && c = 100; //ok
It is called rvalue-reference.
You could bind const reference to a temporary though (both in C++03, and C++11):
int const & c = 100;
-
int c = 100;
It simply defines an object called c and initializes it with 100. No reference here.
int &c = 100
is invalid code, you cannot bind a non-const reference to a temporary.
To make it valid, you need a const reference:
const int &c = 100;
While,
int c = 100
is a valid code. It creates a variable named c of the type int and initializes it with 100.
1) int& c = 100; is illegal, whereas the second one is not.
I understood the reference variable concept.
If you really understood references, are you expecting that after you do c = 101 the constant 100 suddenly turns to 101?
2) No point in answering, since 1) is illegal.
int& i = 100;
Is illegal.
It is legal to say:
int const& i = 100;
const int& i = 100; // same as above
Not particularly useful in this context, but it needs to work for the purposes of function calls:
void foo(int const& i) { ... }
...
foo(100);
Why do constant references not behave the same way as constant pointers, so that I can actually change the object they are pointing to? They really seem like another plain variable declaration. Why would I ever use them?
This is a short example that I run which compiles and runs with no errors:
int main (){
int i=0;
int y=1;
int&const icr=i;
icr=y; // Can change the object it is pointing to so it's not like a const pointer...
icr=99; // Can assign another value but the value is not assigned to y...
int x=9;
icr=x;
cout<<"icr: "<<icr<<", y:"<<y<<endl;
}
The clearest answer.
Does “X& const x” make any sense?
No, it is nonsense
To find out what the above declaration means, read it right-to-left:
“x is a const reference to a X”. But that is redundant — references
are always const, in the sense that you can never reseat a reference
to make it refer to a different object. Never. With or without the
const.
In other words, “X& const x” is functionally equivalent to “X& x”.
Since you’re gaining nothing by adding the const after the &, you
shouldn’t add it: it will confuse people — the const will make some
people think that the X is const, as if you had said “const X& x”.
The statement icr=y; does not make the reference refer to y; it assigns the value of y to the variable that icr refers to, i.
References are inherently const, that is you can't change what they refer to. There are 'const references' which are really 'references to const', that is you can't change the value of the object they refer to. They are declared const int& or int const& rather than int& const though.
What is a constant reference (not a reference to a constant)
A Constant Reference is actually a Reference to a Constant.
A constant reference/ Reference to a constant is denoted by:
int const &i = j; //or Alternatively
const int &i = j;
i = 1; //Compilation Error
It basically means, you cannot modify the value of type object to which the Reference Refers.
For Example:
Trying to modify value(assign 1) of variable j through const reference, i will results in error:
assignment of read-only reference ‘i’
icr=y; // Can change the object it is pointing to so it's not like a const pointer...
icr=99;
Doesn't change the reference, it assigns the value of the type to which the reference refers.
References cannot be made to refer any other variable than the one they are bound to at Initialization.
First statement assigns the value y to i
Second statement assigns the value 99 to i
This code is ill-formed:
int&const icr=i;
Reference: C++17 [dcl.ref]/1:
Cv-qualified references are ill-formed except when the cv-qualifiers are introduced
through the use of a typedef-name or decltype-specifier, in which case the cv-qualifiers are ignored.
This rule has been present in all standardized versions of C++. Because the code is ill-formed:
you should not use it, and
there is no associated behaviour.
The compiler should reject the program; and if it doesn't, the executable's behaviour is completely undefined.
NB: Not sure how none of the other answers mentioned this yet... nobody's got access to a compiler?
By "constant reference" I am guessing you really mean "reference to constant data". Pointers on the other hand, can be a constant pointer (the pointer itself is constant, not the data it points to), a pointer to constant data, or both.
As it mentioned in another answers, a reference is inherently const.
int &ref = obj;
Once you initialized a reference with an object, you can't unbound this reference with its object it refers to. A reference works just like an alias.
When you declare a const reference, it is nothing but a reference which refers to a const object.
const int &ref = obj;
The declarative sentences above like const and int is determining the available features of the object which will be referenced by the reference. To be more clear, I want to show you the pointer equivalent of a const reference;
const int *const ptr = &obj;
So the above line of code is equivalent to a const reference in its working way. Additionally, there is a one last point which I want to mention;
A reference must be initialized only with an object
So when you do this, you are going to get an error;
int &r = 0; // Error: a nonconst reference cannot be initialized to a literal
This rule has one exception. If the reference is declared as const, then you can initialize it with literals as well;
const int &r = 0; // a valid approach
First I think int&const icr=i; is just int& icr = i, Modifier 'const' makes no sense(It just means you cannot make the reference refer to other variable).
const int x = 10;
// int& const y = x; // Compiler error here
Second, constant reference just means you cannot change the value of variable through reference.
const int x = 10;
const int& y = x;
//y = 20; // Compiler error here
Third, Constant references can bind right-value. Compiler will create a temp variable to bind the reference.
float x = 10;
const int& y = x;
const int& z = y + 10;
cout << (long long)&x << endl; //print 348791766212
cout << (long long)&y << endl; //print 348791766276
cout << (long long)&z << endl; //print 348791766340
In the following, would there be a temporary object created before const reference is used to a non-const object?
const int y = 2000;
const int &s = y // ok, const reference to const object.
int x = 1000;
const int &r = x; // any temporary copy here?
If no then, how does this work?
const int z = 3000;
int &t = z // ok, why can't you do this?
No.
A reference is simply an alias for an existing object. const is enforced by the compiler; it simply checks that you don't attempt to modify the object through the reference r.* This doesn't require a copy to be created.
Given that const is merely an instruction to the compiler to enforce "read-only", then it should be immediately obvious why your final example doesn't compile. const would be pointless if you could trivially circumvent it by taking a non-const ref to a const object.
* Of course, you are still free to modify the object via x. Any changes will also be visible via r, because they refer to the same object.
In
int x = 1000;
const int &r = x;
the right-hand side is an lvalue and the type of x is the same as the type of the reference (ignoring cv-qualifications). Under these circumstances the reference is attached directly to x, no temporary is created.
As for "how does this work"... I don't understand what prompted your question. It just works in the most straighforward way: the reference is attached directly to x. Nothing more to it.
You can't do
const int z = 3000;
int &t = z;
because it immediately violates the rules of const-correctness.
The understanding on the Reference (&) answers this question..
Reference is just an alias to the variable that it is assigned to it..
And const is a constraint imposed by the compiler to the variable that is declared as const
int x = 1000;
const int &r = x;
In this case, its a const reference to a non const variable. So you cannot change the data of x with reference variable r(just acts a read only).. yet you can still change the data x by modifying x
const int z = 3000;
int &t = z
In this case, non const reference to const member which is meaningless. You are saying reference can allow you to edit a const member(which is never possible)..
So if you want to create a reference for a const member, it has to be like the first case you mentioned
const int z = 3000;
const int &t = z;
int main(){
int x = 10;
const int&z = x;
int &y = z; // why is this ill formed?
}
Why is initializing non constant reference to int to a constant reference not correct? What is the reason behind this?
Well, why shouldn't it be ill-formed?
It is ill-formed because it breaks the obvious rules of const correctenss. In C++ language you are not allowed to implicitly convert the constant access pass to a non-constant access path. It is the same for pointers and for references. That's the whole purpose of having constant access paths: to prevent modification of the object the path leads to. Once you made it constant, you are not allowed to go back to non-constant, unless you make a specific explicit and conscious effort to do that by using const_cast.
In this particular case you can easily remove the constness from the access path by using const_cast (this is what const_cast is for) and legally modify the referenced object, since the referenced object is not really constant
int main(){
int x = 10;
const int &z = x;
int &y = const_cast<int &>(z);
y = 42; // modifies x
}
Since y isn't const, you would be able to write y = 42 and change z (which is const) too.
Because a const reference is unmodifiable, while a standard reference is.
The compiler assumes that the thing referred to by a const int & is a const int, even though in this case it isn't. You cannot make a non-const reference refer to a const int, because you would then be able to change the (notionally) const int via the reference.
Because
int const x = 10;
int const& z = x;
int& y = z;
y = 42;
would modify a constant variable.
As others say, it would allow one to indirectly change x, which breaks the const-correctness promise. See http://en.wikipedia.org/wiki/Const_correctness