带有数组成员的默认复制分配
我有一个类似于以下内容的类定义:
class UUID
{
public:
// Using implicit copy assignment operator
private:
unsigned char buffer[16];
};
我刚刚有一个单元测试失败,该测试正在验证副本分配是否正常工作。令我惊讶的是,buffer[] 数组中间的一个字节被错误地复制。
我的理解是,默认的复制赋值运算符执行按成员复制,而对于数组成员(不是指向数组成员的指针),则需要按元素复制数组。我错了吗?
我的直觉是,我被一个悬空的指针咬住了,它踩在了数组的中间。但是,当我将这些对象的向量复制到另一个向量时,我会重复看到这种情况。
有人愿意告诉我我哪里出错了吗?
编辑:
对此进行扩展,该类不是 POD 类型 - 它派生自一些抽象基类,因此具有虚拟析构函数。然而,数组是唯一的数据成员,在单元测试中破坏的用法是这样的:
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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的。这是正确的。
您的问题不在于复制赋值运算符(除非您发现了一些不寻常的编译器错误,但这不太可能)。
Yes. This is correct.
Your problem is not with the copy assignment operator (unless you have found some unusual compiler bug, which is unlikely).