【问题标题】:How to copy an array that has been initialized as an smartpointer?如何复制已初始化为智能指针的数组?
【发布时间】:2022-12-16 20:33:06
【问题描述】:

我正在使用 std::unique_ptr<uint8[]> CPPPixelBuffer; 将纹理的像素数据存储为数组。

该数组在构造函数中初始化如下:

SIZE_T BufferSize = WorldTextureWidth * WorldTextureHeight * DYNAMIC_TEXTURE_BYTES_PER_PIXEL;
CPPPixelBuffer = std::make_unique<uint8[]>(BufferSize);

到目前为止,纹理的创建和绘制工作正常。 (如下图所示) TextureData as the are supposed to be

现在我正在尝试使用 for 循环创建该数组的副本。 (我正在使用 for 循环,因为我想稍后只提取部分纹理。但为了演示,我在这个例子中完全复制了数组。)

SIZE_T PartBufferSize = WorldTextureWidth * WorldTextureHeight * DYNAMIC_TEXTURE_BYTES_PER_PIXEL;
std::shared_ptr<uint8[]> PartPixelBuffer(new uint8[PartBufferSize]());

// Get the base pointer of the pixel buffer
uint8* Ptr = CPPPixelBuffer.get();

//Get the base pointer to the new pixel buffer
uint8* PartPtr = PartPixelBuffer.get();

for (int i = 0; i < WorldTextureHeight *WorldTextureWidth * DYNAMIC_TEXTURE_BYTES_PER_PIXEL; i++) {

        *(PartPtr++) = *(Ptr++);
}

delete Ptr;
delete PartPtr;

复制后的像素混合在一起,每次执行这段代码时图片都不一样。 (如下图所示) Wrong Reults

我究竟做错了什么?

【问题讨论】:

  • 您没有明确删除智能指针拥有的指针
  • 谢谢你。我也想知道这个。
  • 另一方面,一个强制性问题:你为什么不使用std::vector

标签: c++ arrays smart-pointers


【解决方案1】:

最后两行是三重错误。

  1. 数组由智能指针管理。你不应该手动delete他们。
  2. 数组是通过new[]创建的。释放内存需要delete[]
  3. 指针未指向数组的开头,因为它们已在循环中递增

    您的代码具有未定义的行为。什么事情都可能发生。

    您应该删除最后两行。复制看起来没问题。

【讨论】:

  • 谢谢你。我怀疑我需要在递增后“重置”指针,所以我得到指向调用 CPPPixelBuffer.get() 的数组开头的指针。但是我该怎么做呢?
  • ”怀疑我需要在递增后“重置”指针“为什么?那不是我说的。
猜你喜欢
  • 2012-10-27
  • 2018-11-06
  • 1970-01-01
  • 2016-06-27
  • 1970-01-01
  • 1970-01-01
  • 2017-09-19
  • 2010-10-11
  • 1970-01-01
相关资源
最近更新 更多