I have the following method which returns the local declared Object by value:
Human Human::getLocalDeclaredHuman() {
Human human;
std::cout << &human << std::endl;
return human;
}
And I call this method:
Human a;
Human b = a.getLocalDeclaredHuman();
std::cout << &b << std::endl;
std::cout << b.getName() << std::endl;
and this is the output of the running program:
0x22fe58
0x22fe58
John Doe
So the variable human which is declared local in the method has the same address as the variable b. I thought return-by-value will create a copy of the object and that the object b has another address like the object human which is declared locally.
My question:
If here b and human have the same address, where is the difference between return-by-value and return-by-reference?
Return Value Optimization.
It isn’t so much that the caller received a reference to the callee’s local variable, but rather the compiler snuck a reference to the caller’s variable into the callee!
getLocalDeclaredHuman.humannever really existed. The compiler was able to optimize away its existence and do all of its work directly onb.And, to answer your question directly, “where is the difference between return-by-value and return-by-refernce?”: In this case, return-by-value means that the single object has the lifetime of
b. If you were to returnhumanby reference, that single object would have the lifetime ofhuman, i.e. it would be destroyed whengetLocalDeclaredHuman()returns.