正确分配 std::vector

Correct allocation for std::vector

本文关键字:vector std 分配      更新时间:2023-10-16

我在将我的 std::vector 交给另一个类时遇到问题。我把数据放到 std::vector 中,然后放到一个名为"Mesh"的类中。"网格"进入"模型"。

// Store the vertices
std::vector<float> positionVertices;
positionVertices.push_back(-0.5f);
positionVertices.push_back(-0.5f);
positionVertices.push_back( 0.5f);
positionVertices.push_back(-0.5f);
positionVertices.push_back(-0.5f);
positionVertices.push_back( 0.5f);
// Put them into a mesh and the mesh into a model
Mesh mesh = Mesh(positionVertices);
Model model = Model(mesh);

在模型类中,我将网格的位置顶点取回,并将其转换为浮点数[]。但看起来,我分配 std::vector 的方式是错误的,因为在模型类中检查 std::vector 时,它的大小为 0。

// Store the vertices
float* dataPtr = &data[0];
glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(float), dataPtr, GL_STATIC_DRAW);

如何将数据正确引入其他类?

我也不确定网格类的构造函数的工作方式。网格:

// Mesh.h
class Mesh
{
public:
    std::vector<float> positionVertices;
    Mesh(std::vector<float>);
    ~Mesh();
};

目.cpp:

// Mesh.cpp
Mesh::Mesh(std::vector<float> positionVertices) : positionVertices(Mesh::positionVertices)
{
}

型号.h:

// Model.h
class Model
{  
public:
Mesh mesh;
unsigned int vertexArray;
unsigned int vertexCount;
Model(Mesh);
~Model();
void storeData(std::vector<float> data, const unsigned int index, const unsigned int size);
};

型号.cpp:

// Model.cpp
Model::Model(Mesh mesh) : mesh(Model::mesh)
{ ... }
// Mesh.cpp
Mesh::Mesh(std::vector<float> positionVertices) :
positionVertices(Mesh::positionVertices) // Here's the problem
{
}

初始值设定项列表中的positionVertices Mesh::positionVertices ,因此您将其分配给自身。

positionVertices(positionVertices)

另外,更改

Mesh::Mesh(std::vector<float> positionVertices) :

Mesh::Mesh(const std::vector<float>& positionVertices) :

因此,您不会对矢量进行不必要的复制。

相关文章: