我可以安全地复制 vector<array> 吗?

Can I safely copy vector<array>?

我有一个 vector<array<float,3>> 用作渲染的 3D 坐标列表。
我可以简单地使用带有 sizeof(array<float,3>) * vector.size() 作为 count 参数的 memcpy 吗? vector的内存是否可以安全复制?

€dit:这是我的代码片段。 我的问题现在措辞有点不正确。

vector<array<float,3>> vertexPositions;
//read VertexPositions, one line represents a vertex position and put them into vertexPositions with push_back();

D3D11_BUFFER_DESC bufferDesc;
//initialize Buffer Description;

D3D11_SUBRESOURCE_DATA bufferInitialData;
bufferInitialData.pSysMem = vertexPositions.data(); //pSysMem is a void* and expects a sequence of floats

pSysMem 只是一个 void* 并且该结构有一个额外的大小参数,我将其设置为 sizeof(array<float,3>) * vector.size()

array<float,3> 是简单可复制的,vector.data() 是一个连续的块,是的,memcpy 是安全的,但我认为这是不好的做法,希望你有一个好的不传递指针的原因,复制向量而不是原始数据或使用 std::copy 代替。

要检查类型是否可简单复制,您可以使用 std::is_trivially_copyable

Is the memory of vector safe to copy?

是的,向量在这里没有任何特殊作用,元素的打包方式与数组的打包方式相同。你可以很容易地看到这一点,因为说 data() return 是一个可以作为数组访问的指针(对于 [0][myvec.size() - 1]),直到执行使该 [= 无效的操作为止=27=](例如破坏向量或调整向量大小)。

I want the floats to be tightly packed (since they will be sent to the GPU), does this allow me to do that?

因此,这基本上意味着确保您在向量 中存储的类型满足要求。 (例如,您实际上想要 3 浮点 RGB 格式,而不是整数格式或 RGBA 或 RGBX 4 元素格式之一)。根据你使用的 API ,你甚至可以直接给它矢量数据,而无需复制到单独的数组(例如 ID3D11Device::CreateBuffer 接受 pInitialData 并且如果你将正确的类型存储在向量,您可以将 pSysMem 设置为 myvector.data()).

您可以像 float[][3] 一样使用 std::array<float, 3> *。您没有获取矢量地址的其中之一。

std::vector<std::array<float,3>> vertexPositions;
//read VertexPositions, one line represents a vertex position and put them into vertexPositions with push_back();

D3D11_BUFFER_DESC bufferDesc;
//initialize Buffer Description;

D3D11_SUBRESOURCE_DATA bufferInitialData;
bufferInitialData.pSysMem = static_cast<void *>(vertexPositions.data()); //pSysMem is a void* and expects a sequence of floats