When passing a struct in C/C++ by value the struct contents must be copied. How do compilers achieve that? I.e., which assembly instructions are usually emitted for this copy?
How fast are these, when, e.g. compared to a call to memcpy?
Now consider this code:
struct X { int i, j, k; };
void foo(X x);
void foo( int i, int j, int k);
Is there any difference between calling foo(X) and foo(int,int,int) or might the generated assembly code be the same (considering the passing of parameters)?
How do compilers achieve that?
They call the copy constructor for that class/structure. The implicitly generated one if you don't provide one or the one you provide.
How fast are these, when, e.g. compared to a call to
memcpy
?
Depends on the class and its members. Profiling should give you a clearer picture.
However, using memcpy
to copy class instances should be avoided.
How do compilers achieve that?
They perform a shallow copy for that structure. For all practical purposes you can consider it same as memcpy
.
Obviously, if there is a constructor for the struct
or class
, then the constructor is called.
If there isn't a constructor, it is entirely up to the compiler, but most likely, for three integer sized objects, it will probably be three individual mov
instructions. For larger structures, it's either a call to memcpy
or an inlined version similar to memcpy
.
It is also quite likely that if the structure is VERY large (several megabytes), that true memcpy
is faster than the inlined version, and the compiler may not realize this and use the inlined version anyway. But most of us don't use megabytes large structs, so I don't think generally that's something to worry too much about. Copying structs onto the stack as arguments, if the struct is megabytes large, is probably not a great idea in the first place, given the restricted size of a typical stack.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With