I am struggling to grasp rvalues in C++. Specifically, I don't understand where they are allocated and why they need to be immutable. Let's assume I have the following code:
std::string str = std::string();
const std::string& sref = std::string();
The first line creates an object in the stack. The object str
is a mutable object and I can do whatever I want with it. The expression on the right of the assignment is rvalue while str
is lvalue as far I've understood.
The second line creates an object in the current function stack ( I presume ) and it returns a const reference to it. The object so created is immutable. Again, the right side of the assignment is a rvalue, but this time I got a reference to rvalue. All reference, to a rvalue MUST be const because according to C++ standard you cannot change the value of rvalue. First question where is sref
allocated in the current function stack? Why must it be immutable? I really don't understand why if the object is in the stack, I cannot just modify it.
If an object is immutable, it would make sense to have just one instance of it and then make all references in the application to point to it.
const std::string& ref_1 = std::string();
const std::string& ref_2 = std::string();
are these two refs referring to the same object in C++?