Wrong use of std::copy?

依然范特西╮ 提交于 2019-12-04 11:42:53

The immediate problem is here:

std::copy(&ui32, &ui32 + sizeof ui32, &v[4]);
                       ^^^^^^^^^^^^^

&ui32 has type uint32_t *, and adding anything to that already takes into account the object's size. You're effectively attempting to copy sizeof ui32 uint32_t objects, but you only have a single one, so you should be using + 1.

That aside, using std::copy with pointers of different types is likely not to give you the results you expect. It has the effect of v[4] = ui32;, which works as long as ui32 is inside Byte's range, which it is here, but that's not something you can rely on in general.

The second std::copy has roughly the same problem, but in the opposite direction.

What you could do is:

std::copy((Byte*) &ui32, (Byte*) (&ui32 + 1), &v[4]);
// or std::copy((Byte*) &ui32, (Byte*) &ui32 + sizeof ui32, &v[4]);
...
std::copy(&v[4], &v[4] + sizeof ui32, (Byte*) &result);

The problem isn’t with std::copy but with pointer arithmetic. As you’ve said, “a pointer IS an iterator”. But more importantly, it’s strongly typed. So a pointer-to-uint32_t is different from a pointer-to-unsigned char.

Adding &ui32 + sizeof ui32 effectively treats ui32 as if it were the beginning of a contiguous array with 4 elements (of type uint32_t).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!