Lately I've been analyzing some parts of an older code where in some cases value returned from function was assigned to const
variable and sometimes to const&
. Out of curiousity I've switched to the dissasembly to see the differences. But before getting to the point let me draw a simple example to have some code to refer to:
struct Data
{
int chunk[1024];
};
Data getData()
{
return Data();
}
int main()
{
const std::string varInit{ "abc" }; // 1
const std::string varVal = "abc"; // 2
const std::string& varRef = "abc"; // 3
const Data dataVal = getData(); // 4
const Data& dataRef = getData(); // 5
return 0;
}
The following disassembly of the above code was acquired with VS2015 with optimizations disabled.
I'm no asm specialist but at first glance I'd say that for
(1)
and (2)
there are similar operations performed. Nevertheless, I'm surprised that (3)
carries two additional operations (lea
and mov
) comparing to previous versions where the const&
was not used during variable value assignment.
Same can be observed when the data is returned from a function by value. (5)
carries two more operations in relation to (4)
.
The questions are quite narrow:
- Where do these additional operations come from and what is their purpose here? Not in general like here: What's the purpose of the LEA instruction but in the presented context.
- Can this influence the performance at least for objects for which the underlaying data size is negligible? (in contrast to
Data
struct used in the example) - Would this have any impact when the optimization is turned on? (for release builds)
By the way, I've already read Why not always assign return values to const reference? about pros and cons of using const and const& when assigning values which can be somewhat related but is not a part of the question.