Is there a difference between this:
MyClass c = getMyClass();
calculate(c.value);
and this:
calculate(getMyClass().value);
in the scope of performance and memory allocation?
Yes, there is a fairly serious difference. In the first case, c
is an lvalue, and it will not be destroyed until the end of the scope. This can delay useful things like reosurce cleanup. More problematically, it being an lvalue means that it cannot be moved, but must be copied, which is inefficient for many classes but downright illegal for some very important classes, like unique_ptr
.
In the second case, the compiler cleans up the temporary right away, so all resources are released promptly, and it being an rvalue gives the compiler more freedom to optimize and permits move semantics.
This is still true when value
is a member or member function, as the result of both can inherit value category from their parent object.
You should always scope objects to the minimum scope required, and if you don't need to access c
later, then you should use the temporary.