In the following code snippet my function tries to return it's 'by-value' argument as a 'by-value' return-value. I watched a video where it stated: "It is physically not possible to do copy elision here.." but I dont see why the we couldn't use the same memory address for the function parameter as well as the return value.
std::string foo(std::string s){
return s;
}
I tried to understand it by watching a video but can't see where this would fail to do copy elision.
Regardless of who is in charge of destroying function arguments, they cannot also be the result object created at the call site. This is required by C++17, and would be difficult/impossible to implement with NRVO(1) for function parameters. Consider this function and call:
What happens is:
std::string sargument is constructed from"..."If the caller is in charge of destroying
s, how is the caller supposed to know thatris the same object ass? It's impossible to know without looking inside the definition offoo, or it would need to get additional run-time information that informs it about which parameter (if any) is the same object as the result object.If the callee is in charge of destroying
s, that would mean thatrcannot besbecausesis destroyed byfoo.(1) NRVO means Named Return Value Optimization.
(2) The relevant wording for step 3 is in [expr.call] p6: