Search code examples
c++arraysvectormemcpy

Can I safely copy vector<array>?


I have a vector<array<float,3>> to use as a list of 3D Coordinates for my rendering.
Can I simply use memcpy with sizeof(array<float,3>) * vector.size() as the count argument? Is the memory of vector safe to copy?

€dit: Here is a snippet of my code. My question is a bit incorrectly phrased now.

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 is simply a void* and the structure has an additional size parameter that i set as sizeof(array<float,3>) * vector.size()


Solution

  • Is the memory of vector safe to copy?

    Yes, a vector doesn't do anything special here, and elements will be packed the same as they would be for an array. You can see this easily because say data() returns a pointer that can be access as an array (for [0] up to [myvec.size() - 1]) until an operation is performed that invalidates that return (e.g. destroying or resizing the vector).

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

    As such this basically means make sure the type you store in the vector meets the requirements. (e.g. that you actually want a 3-float RGB format, and not one of the integer formats or a RGBA or RGBX 4-element format). Depending on the API you use, you can probably even give it the vector data directly, without copying to a separate array (e.g. ID3D11Device::CreateBuffer takes a pInitialData and if you store the right type in the vector, you can just set pSysMem to be myvector.data()).