views:

50

answers:

1

I've got a class definition similar to the following:

class UUID
{
  public:
    // Using implicit copy assignment operator

  private:
    unsigned char buffer[16];
};

I've just had a unit test fail on me that was verifying that copy assignment worked properly. To my surprise, one byte in the middle of the buffer[] array was copied incorrectly.

My understanding is that the default copy assignment operator performs memberwise copy, and that for array members (not pointer-to-array members) that entails elementwise copy of the array. Am I mistaken?

My gut feeling here is that I've been bitten by a dangling pointer somewhere that has stomped on the middle of my array. But, I'm seeing this repeatably when, e.g. I copy a vector of these objects into another vector.

Anybody care to tell me where I've gone wrong?

Edit:

To expand on this a bit, the class is not a POD type--it derives from a few abstract base classes and thus has a virtual destructor. However, the array is the only data member, and the usage which broke in the unit test was this:

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);
}
+2  A: 

My understanding is that the default copy assignment operator performs memberwise copy, and that for array members (not pointer-to-array members) that entailed elementwise copy of the array.

Yes. This is correct.

Your problem is not with the copy assignment operator (unless you have found some unusual compiler bug, which is unlikely).

James McNellis
Thanks for confirming my suspicions. Time for some debugger magic, I think...
Drew Hall
@Drew: Good luck! :-)
James McNellis
@James: Thanks! I think I'm going to need it. BTW, I added some extra text/test case code in an edit. I don't think it changes anything but thought I'd bring it to your attention anyway.
Drew Hall