使用数组成员的默认副本分配 [英] Default copy assignment with array members

查看:215
本文介绍了使用数组成员的默认副本分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类定义类似于以下内容:

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?

编辑:

为了扩展这一点,类不是POD类型 - 它来自一些抽象基础类,因此具有虚拟析构函数。但是,数组是唯一的数据成员,在单元测试中破坏的用法是:

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);
}


推荐答案


我的理解是,默认的复制赋值操作符执行成员复制,而数组成员(不是指针到数组成员)需要数组的元素复制。

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.

是的。这是正确的。

您的问题不是使用复制赋值运算符(除非您发现了一些不常见的编译器错误,这是不可能的)。

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

这篇关于使用数组成员的默认副本分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆