Reputation: 369
Since c++ provides references to rvalues i.e. rvalue references which are mainly used to perform move semantics and other memory efficient tasks. But in the following case reference is changing the value of an literal but as we know that literals are read only so how could a reference change the value of some read only variable. Does a rvalue reference allocate it's own memory or it simply changes the value of literal?
#include <iostream>
using namespace std;
int main()
{
int a = 5;
int&& b = 3;
int& c = a;
b++;
c++;
cout << " Value for b " << b << " Value for c " << c << endl;
}
Secondly, when a temporary object is assigned with a reference, reference works with the data of that object. But according to the definition of temporary objects they are deleted as when the expression using them ends. How could the reference act as an alias name to that temporary object if that temporary object is out of memory?
Upvotes: 11
Views: 1341
Reputation: 154035
Numeric literals can't be bound to any reference, neither an rvalue reference nor an lvalue reference. Conceptually, a numeric literal creates a temporary object initialized from the literal value and this temporary can be bound to an rvalue references or to const
lvalue reference (int const& r = 17;
). It seems the relevant quote on literals is 5.1.1 [expr.prim.general] paragraph 1:
A literal is a primary expression. Its type depends on its form (2.14). A string literal is an lvalue; all other literals are prvalues.
When binding a reference directly to a temporary, it's life-time gets extended until the reference goes out of scope. The relevant section for the life time issue is 12.2 [class.temporary] paragraph 5:
The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:
- A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits.
- A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call.
- The lifetime of a temporary bound to the returned value in a function return statement (6.6.3) is not extended; the temporary is destroyed at the end of the full-expression in the return statement.
- A temporary bound to a reference in a new-initializer (5.3.4) persists until the completion of the full-expression containing the new-initializer.
Upvotes: 14