问题
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);
}
回答1:
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).
来源:https://stackoverflow.com/questions/3681265/default-copy-assignment-with-array-members