调用draw()函数时,c ++向量大小为零

时间:2019-09-05 18:53:42

标签: c++ opengl

我创建了一个向量来存储96个计算值。该函数很好,可以返回大小为96的向量。

但是,当我在绘图函数中调用矢量时,其大小为零,从而导致访问冲突。

vector<float>Icosphere::calcIcosphere() {
//variables
   vector<float> vertices (12*8)
   //computing values
return vertices;   //at this point the size=96
}

void Icosphere::drawIcosphere() const{
//variables
//create VAO
//generate buffer for VBO & IBO
vector<float> vertices; //here its size=0 and stays 0
//bind buffers and fill with vector and indices
....
glDrawElements(...); //causing access violation
...
}

我不明白为什么向量返回值后变为0。我想我错过了一些基础知识。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

一个作用域中的局部变量与另一个作​​用域中的局部变量完全分开,即使它们具有相同的名称。一个简单的例子:

void foo() {
    int bar = 1;
}

void baz() {
    int bar = 2;
}

这两个bar变量是不同的对象,它们之间没有关联。实际上,在每次调用每个函数时,都会创建一个新的本地对象。此外,除了在声明它们的各个函数中之外,这些对象甚至不存在。

当您声明这样的变量时:

vector<float> vertices;

您默认对其进行初始化,它将是一个空向量。在此之前是否存在另一个向量变量对该向量的内容没有影响。

答案 1 :(得分:0)

函数中那些名为“ vertices”的std :: vector-s是完全不同的实例,因此更改一个不会影响另一个。您的代码可能看起来应该像这样:

void Icosphere::drawIcosphere() const{
//variables
//create VAO
//generate buffer for VBO & IBO
vector<float> vertices = calcIcosphere();
//bind buffers and fill with vector and indices
....
glDrawElements(...); //causing access violation
...
}