I know rvalue is the value that can not be referenced. And for decreasing the operation of memory allocation, the rvalue reference as well as move semantics are created.
To most of the situation, the reference copy happened in return
like below
// SomeObject implements the move semantics
SomeObject function(){
auto obj = new SomeObject();
return obj;
}
int main()
{
auto obj = function();
return 0;
}
Here, the move semantics happened in return
. I’m not sure about how exactly this work in memory allocation level. The SomeObject
is created on heap and the function works on its own stack frame. When the function ends, its stack is deleted. Hence, all data on stack disappears.
However, for obj
with move semantics, the internal pointer was assigned to new SomeObject
in main
, the data do not be freed. Therefore, can I just simply think that the rvalue reference for SomeObject
is just reusing the data on stack? And when compiler call the de-constructor of SomeObject
with move semantics, the compiler won’t free the data owned by it?
BTW, I’m learning rust, thus I want to know the work mechanism of rvalue reference and move semantics from aspect of memory allocation and ownership then this question comes into my mind.