Default copy assignment with array elements

I have a class definition similar to the following:

class UUID { public: // Using implicit copy assignment operator private: unsigned char buffer[16]; }; 

I just got a unit test error that checks if the copy works correctly. To my surprise, one byte in the middle of the buffer [] array was copied incorrectly.

My understanding is that by default the assignment operator performs a phased copy, but for array members (not pointer-array elements), which entails an elementary copy of the array. Am I mistaken?

The feeling of my feeling is that I was bitten by a dangling pointer somewhere that stomps in the middle of my array. But I repeat this when, for example, I copy the vector of these objects to another vector.

Anyone want to tell me where I was wrong?

Edit:

To extend this class a little, the class is not a POD type - it comes from several abstract base classes and, therefore, has a virtual destructor. However, the array is the only data member, and the usage that broke in the unit test was as follows:

 const int n = 100; std::vector<UUID> src, dst; src.reserve(n); dst.resize(n); for (int i = 0; i < n; ++i) { UUID id; src.push_back(id); } for (int i = 0; i < n; ++i) { dst[i] = src[i]; } bool good = true; for (int i = 0; i < n; ++i) { const bool thisGood = (dst[i] == src[i]); std::cout << "i = " << i << " -> src = '" << src[i] << "', dst = '" << dst[i] << "', src == dst ? " << thisGood << '\n'; good = (good && thisGood); } 
+7
c ++ arrays assignment-operator
source share
1 answer

I understand that the copy assignment operator, by default, performs the correction in order, but for the members of the array (and not the pointer-elements-arrays), which entail an elemental copy of the array.

Yes. It is right.

Your problem is not related to the copy assignment operator (if you did not find an unusual compiler error, which is unlikely).

+10
source share

All Articles