数组成员的默认副本分配

时间:2021-11-10 05:33:33

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.

我刚刚对我进行了单元测试失败,验证了副本分配是否正常工作。令我惊讶的是,buffer []数组中间的一个字节被错误地复制了。

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:

为了扩展这一点,该类不是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);
}

1 个解决方案

#1


11  

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).

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

#1


11  

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).

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