Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does C/C++ copy structs?

Tags:

c++

c

copy

struct

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)?

like image 586
gexicide Avatar asked Oct 17 '25 18:10

gexicide


2 Answers

In C++

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.

In C

How do compilers achieve that?

They perform a shallow copy for that structure. For all practical purposes you can consider it same as memcpy.

like image 199
Alok Save Avatar answered Oct 20 '25 08:10

Alok Save


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.

like image 34
Mats Petersson Avatar answered Oct 20 '25 07:10

Mats Petersson