Answer the question
In order to leave comments, you need to log in
Why can't return object by value in non-const &?
https://godbolt.org/z/dqTffoGPn
In assembly code, when calling a struct sf ( void ) function that returns an object by value, the memory for the object is actually allocated inside the main() stack frame beforehand. The address of this object is secretly passed to the function, and the object is not created inside the function. Very cool.
But do I understand correctly that the ban on returning "object by value" in a non-const reference is a purely syntactic rule, and not a technical limitation?
Answer the question
In order to leave comments, you need to log in
The first is Retrun Value Optimization. The compiler sees that the result of the function is used to initialize the variable and instead of allocating memory for a temporary object and copying it immediately fills the result.
About the link. The result of the function in your case is prvalue
in the same link, it says:
An rvalue may be used to initialize a const lvalue reference , in which case the lifetime of the object identified by the rvalue is extended until the scope of the reference ends.
An rvalue may be used to initialize an rvalue reference , in which case the lifetime of the object identified by the rvalue is extended until the scope of the reference ends.
const int& r1 = f();
int&& r2 = f();
const struct s & ref = f();
This mechanism is called "prolonging the life of a temporary object."
You can write like this.
The main reason for converting a temporary object to only const T& and T&& is subtle errors in function superposition.
Namely, in no case should we pass a temporary object to a function that accepts s&.
struct s && ref = f();
void modify(s& arg) { ++arg[1]; }
...
modify(f());
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question