Вопрос

Consider copy a simple struct which doesn't require special copy semantics.

struct A
{
    char i
    int i;
    long l;
    double b;
    //...maybe more member
}
struct A a;
a.c = 'a'; //skip other member just for illustrate
struct A b;
memset(&a, 0, sizeof(a));
b.c = a.c;
//...for other members, the first way to assign
memcpy(&b, &a, sizeof(b)); //the second way
b = a;    //the third way

The 3 methods do the same thing, and it seems all of them are correct. I used to use 'memcpy' for copying simple structs, but seems now '=' can do the same thing. So is there any difference between using memcpy and '='?

Это было полезно?

Решение

memcpy treats the structure as a contiguous array of bytes, and just copies all of them. As a result, it will always copy the padding bytes after members.

= is only required to copy the members. It might or might not copy the padding.

Другие советы

I would get in the habit now of using = instead of memcpy. In C the difference is minimal at best but once you graduate to C++, as indicated by the question, the difference is huge. Consider for example

struct C {
  C() { }
  ~C() { } 
}

C local1;
C local2;
memcpy(&local2, &local1, sizeof(C));

In this case the the constructor for local2 is run at the declaration point. However the destructor for that value is never run. Instead it's members are magically replaced with memcpy and the destructor is run on the memcpy bits. If C happened to allocate any resources this can easily lead to leaks.

Any of the three methods -- manually assigning each member, assigning the entire struct, or using memcpy -- will result in all the members of b being the same as the corresponding members of a, which is all you should care about. The potential differences are in the value of pad bytes -- memcpy will copy them, assigning individual members won't, and assigning the entire struct may or may not -- it's up to the implementation. Some implementations will just use memcpy to assign structs, some will assign member by member, and some will do one or the other depending on such factors as the size of the struct.

I recommend using struct assignment -- it's the simplest, the shortest, and the most problem-oriented. Leave the implementation details up to the compiler. Also, in C++ you can define the assignment operator yourself for greater control and flexibility, and memcpy is frowned on and can have bad effects with classes (see JaredPar's answer).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top