11

eg, it puzzles me:

struct A {
//  some fileds...
    char buf[SIZE];
};

A a;
a = a;

Through A's field buf, it looks like probably that the default assign operation will call something like memcpy to assign an object X to Y, so what if assign an object to itself and there are no explicit assign operation defined, like a = a; above.

memcpy manual page:

DESCRIPTION

The  memcpy() function copies n bytes from memory area src to memory area dest.  The memory areas must not overlap.  Use memmove(3) if the memory areas do overlap.

If use memcpy, there may some undefined behavior occur.

So, what's the default assign operation behavior in C++ object?

12
  • 1
    The problem with overlap is if you are copying from a region that gets overwritten by another part of the region - that is, you are inserting a character into a string, and do memcpy(&a[index+1], &a[index], len-index);. But memcpy(a, a, sizeof(a)) would be fine. Aug 6, 2013 at 12:13
  • 1
    @R.MartinhoFernandes Would you be so kind and enlighten me what that exception is?
    – nikolas
    Aug 6, 2013 at 12:13
  • 3
    @nijansen It's string literals. An example of a pair of literals that could be stored overlapping is "bar" and "foobar". (It isn't a problem for this scenario because those arrays are const.) Aug 6, 2013 at 12:17
  • 3
    @MatsPetersson memcpy(a, a, sizeof(a)) is not fine, src and dst (wholly) overlaps.
    – nos
    Aug 6, 2013 at 12:17
  • 3
    Ok, let me rephrase that: It may be undefined, but the danger with overlapping regions isn't when the overlap is COMPLETE, that is, you are copying things from location X to location X, but when there is an offset between the source and destination, where the source, source+length and destination, destination+length overlap, because the writes of the destination will at some point overwrite the source. If you overwrite directly, it is much less likely to cause a problem. Of course, it's also a complete waste of time to copy 200 bytes over itself. Aug 6, 2013 at 12:25

4 Answers 4

14

The assignment operator is not defined in terms of memcpy (§12.8/28).

The implicitly-defined copy/move assignment operator for a non-union class X performs memberwise copy/move assignment of its subobjects. The direct base classes of X are assigned first, in the order of their declaration in the base-specifier-list, and then the immediate non-static data members of X are assigned, in the order in which they were declared in the class definition. Let x be either the parameter of the function or, for the move operator, an xvalue referring to the parameter. Each subobject is assigned in the manner appropriate to its type:

[...]

— if the subobject is an array, each element is assigned, in the manner appropriate to the element type;

[...]

As you see, each char element will be assigned individually. That is always safe.

However, under the as-if rule, a compiler may replace this with a memmove because it has identical behaviour for a char array. It could also replace it with a memcpy if it can guarantee that memcpy will result in this same behaviour, even if theoretically such a thing is undefined. Compilers can rely on theoretically undefined behaviour; one of the reasons undefined behaviour exists is so that compilers can define it to whatever is more appropriate for their operation.

Actually, in this case a compiler could take the as-if rule even further and not do anything with the array at all, since that also results in the same behaviour.

0
4

Default assign (and copy) behaviour does not memcpy the whole class, which would break things. Each member is copied using their copy constructor or assignment operator (depending on operation). This is applied recursively for members and their members. When a basic data type is reached, it simply performs a straight copy of data, similar to memcpy. So an array of basic data types may be copied similar to memcpy, but the whole class is not. If you add std::string to your class its = operator would be called, alongside copy of array. If you used array of std::string, each string in your array will have their operator called. They won't memcpy.

11
  • 2
    That answer ist partially correct, but does not include the specific case the OP asks about.
    – Arne Mertz
    Aug 6, 2013 at 12:16
  • As memcpy is not used, the violation of memcpy rules is not relevent any more. But I should have discussed self-assignment.
    – Neil Kirk
    Aug 6, 2013 at 12:17
  • Actually I am not sure how default operator handles self-assignment. My hunch is that it doesn't explicitly, and depends upon members that must prevent such a thing, to do their own check in their custom assignment operator.
    – Neil Kirk
    Aug 6, 2013 at 12:20
  • 1
    @NeilKirk Why should the compiler do anything special with regards to self assignment? (For that matter, why should a user defined assignment operator worry about self assignment?) Aug 6, 2013 at 12:28
  • 1
    @NeilKirk You can find a lot of wrong information if you search the web. In general, if you need a check for self assignment, your assignment operator is broken. (And a correctly written implementation of std::vector<>::operator= doesn't need to check for self assignment. Although it might for reasons of optimization; vector assignment is very expensive.) Aug 6, 2013 at 14:22
0

Some limited experimentation tells me that g++ completely removes any attempt to copy a = a; [assuming it is obvious - I'm sure with sufficient messing about with pointers, it will eventually be possible to copy the same object over itself, and get undefined behaviour].

1
  • 2
    It won't get UB, it is defined in terms of element-wise copy (§12.8,28), and element-wise self-assignment is well-defined.
    – Arne Mertz
    Aug 6, 2013 at 12:24
-1

If use memcpy, there may some undefined behavior occur.

It's an implementation detail how the given class will be copied. Both memcpy() function and copy constructor will be converted into some machine code. However your objects in memory should not overlap because default assignment does not guarantee you'll have a proper result in case they overlap.

So, what's the default assign operation behavior in C++ object?

As in other responses, the behaviour is such that it will call assignments on all class/struct members recursively. However technically, as in your case, it may just copy whole block of memory, especially if your structure is POD (plain old data).

4
  • This is wrong. The implicit copy constructors work fine with self-assignment. (And that's irrelevant, and the example is about assignment not initialisation) Aug 6, 2013 at 12:29
  • What is wrong exactly? I was referring to overlapping objects, not self-assignment. With overlapping objects, the behaviour is undefined.
    – Karadur
    Aug 6, 2013 at 12:33
  • Of the copy constructor? No, it isn't. (How do you call the copy constructor with overlapping objects?) Aug 6, 2013 at 12:37
  • Right, I incorrectly mentioned copy constructor, that had to be 'default assignment'. Will correct that, thanks. Although copy constructor may also behave incorrectly when say you use a placemnent new consecutively on overlapping blocks of memory.
    – Karadur
    Aug 6, 2013 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.