Home > OS >  static object calls constructor at wrong time
static object calls constructor at wrong time

Time:07-28

I have an opengl batch renderer, which has a static vao, vbo, ebo etc. problem is, int the constructor of those are opengl methods. now, because they are static the opengl methods like glGenBuffers get called before opengl has been initialized.


so you can get a better picture, this is how it looks:

class renderer2d
{
private:
    static vertex_array vao;
    static vertex_buffer vbo;
    static index_buffer ibo;

public:
    static void draw();
    static GLuint create_quad(glm::vec2 position, glm::vec2 size, GLfloat angle, glm::vec4 color);
}

and int the constructor of e.g. vao:

vao()
{
    //some sort of opengl method, that gets called without opengl being initialized
    glGenVertexArrays(1, &id);
}

btw, i dont only want to "solve" the problem while keeping the "static solution", if you have different ideas on how to do this, please tell me

CodePudding user response:

One trick is to delay initialisation of the object like this:

renderer2d& get_renderer()
{
    static renderer2d renderer;
    return renderer;
}

This method works for any class, it does not require the renderer itself to have static data. The function can also be a static member of the class, as part of the Meyers singleton design.

  • Related