Reputation: 150
I'm curious about the optimisations that C++ compilers do when it comes to moving data around during run-time. Recently, I've been thinking about how classes are passed through the code as I know that if you pass a bool
to a function you don't need to define it as const&
but if you have, for example, a std::vector<T>
then typically you would use const&
as this tends to be larger than 64 bits and thus is more efficient to do so.
Now, if you had a class
which consists of two variables, a uint8_t
and a int8_t
, would the compiler, under the covers, move this class around as it would a single int16_t
or uint16_t
? Similarly, with a class with two int32_t
would it be treated in the same manner when moving around in memory as a single int64_t
?
Upvotes: 2
Views: 63
Reputation: 2679
Yes, the compiler will, by default, copy an int64_t
and a class or struct containing two int_32_t
the same way. Both cases are simply 8 bytes of raw memory on mainstream architectures, so at the low level of copying data they will be treated as such. (For classes and structs this behavior can be changed by overriding the copy/move constructor/assignment operator.)
Copies are done as-if the bytes of memory are copied one-by-one from location to another. One optimization the compiler might do is store the values in a register instead of main memory if the memory address of the value is not used. The fact that the bytes of memory might represent a class or struct don't prevent the compiler from making that optimization.
A standards-compliant compiler could be written that would treat int64_t
and a struct of 2 int_32_t
differently, but in practice it doesn't make sense to do so.
Upvotes: 3