简体   繁体   中英

Constructor called at wrong time

This is less of a plea for help over a problem, and more of a question about something peculiar discovered after solving a problem. I was working on my beginner OpenGL game and was attempting to write an OOP friendly rendering file. All vbo data was being stored in a model class, where it was uploaded and buffered in the constructor.

Vastly simplified structure of this from main would look something like:

int main(){
    vector <Model> Models;

    Graphics.GLInit();

    Models.push_back(Model(vertices,texcoords,36,0));

    Graphics.EnableAttributePointers();

    main loop
    {
        Graphics.draw(Models,Textures,Entities);
    }
    return 0;
}

Constructor looked like:

Model::Model(vector <vec3> &vertices,vector <vec2> &texcoords,int NumVertices,int StartVertex)
{
    iNumVertices=NumVertices;
    iStartVertex=StartVertex;

    Vertices=vertices;
    Texcoords=texcoords;

    glGenBuffers(1,&vboVertex);
    glGenBuffers(1,&vboTexcoord);
    glBindBuffer(GL_ARRAY_BUFFER,vboVertex);
    glBufferData(GL_ARRAY_BUFFER,Vertices.size()*12,Vertices.data(),GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER,vboTexcoord);
    glBufferData(GL_ARRAY_BUFFER,TexCoord.size()*8,TexCoord.data(),GL_STATIC_DRAW);
}

Upon calling glDrawArrays in the drawing function a segmentation fault would occur:

0xC0000005 cannot access 0x00000000 yadda yadda.

So I checked over everything countless times, making sure it all made sense. Eventually I tore apart the program, making a simpler version in which the same exact code is being used without a model class. That worked fine. Figuring something was wrong with the Model class, I eventually placed the buffering code into a separate function to be called directly after the constructor. This fixed it.

Anyways, all this begs the question of why the constructor was seemingly being called upon out of sequence; before the GLInit code. That, or there is some behavioral quirk of constructors which I am unaware of, wherein the OpenGL state machine cannot be properly modified by them for some bizarre reason. My knowledge of C++ is only spare time highschooler level, so am I missing something obvious here?

I am thinking since you are creating vector of Model, the following code

Models.push_back(Model(vertices,texcoords,36,0));

actually makes a COPY (copy constructor will be called) pushes the copy into the vector. Then the original is deleted.

It would be interesting to see the actual data members of class Model and also what is the datatype of "vec3" and "vec2"?

Can we see the destructor function also?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM