What happens when you assign a literal constant to an rvalue reference?

This is admittedly an insignificant question, which is mainly due to curiosity. Suppose we have:

int x = 5; int&& xref = std::move(x); std::cout << "Before assignment x: " << x << std::endl; std::cout << "Before assignment xref: " << xref << std::endl; xref = 10; std::cout << "After assignment x: " << x << std::endl; std::cout << "After assignment xref: " << xref << std::endl; 

Expected Result:

 // Before assignment x: 5 // Before assignment xref: 5 // After assignment x: 10 // After assignment xref: 10 

It makes sense. std::move converts x to the value of x and allows you to bind its memory to xref and change its contents accordingly. Now let's say that we have the following:

 int&& xref = 5; std::cout << "Before assignment xref: " << xref << std::endl; xref = 10; std::cout << "After assignment xref: " << xref << std::endl; int x = 5; std::cout << "After assignment x: " << x << std::endl; 

The output is intuitive:

 // Before assignment xref: 5 // After assignment xref: 10 // After assignment x: 5 

This is a common sense. We expect to be able to bind the constant literal 5 to xref , because 5 is the value of prvalue. We also expect xref be volatile. We also expect that the value of the constant literal 5 not modified (as shown somewhat pedantically in the last two lines of the above fragment).

So my question is: what exactly is going on here? As C ++ knows, do not change the value of the constant literal 5 , but keeping a sufficient identifier for xref to know that it has been changed to 10 by assignment. Is a new variable created when assigning xref when it is bound to a constant literal? This question never arose in C ++ 03, since only const references could be related to rvalues.

+6
source share
2 answers

A temporary structure is created, initialized from the value of the literal, and it lasts as long as the link. You can do what you like with this object.

In terms of lifetime, it is the same as if you wrote const int& x = 5 ; only, there, that you are working with an automatically created temporary object is masked, because const does not allow you to prove it with a mutation.

[C++14: 8.5.3/5]: [..] If T1 is a non-class type, the temporary type "cv1 T1 " is created and initialized with copy (8.5) from the initializer expression. The link is then tied to a temporary one. [..]

+4
source
 int&& xref = 5; 

... creates a temporary initialization from 5, whose lifetime extends to the end of the block.

Appointment

 xref = 10; 

changes the meaning of the still living temporary.

+5
source

All Articles