c++objectglobal

How to do this the right way? Declaring static object in function


The way I did it works, but feels like unbelievably bad programming.

void draw_display() 
{
    static DISPLAY mydisplay = DISPLAY(parameters);
    mydisplay.set_orientation(0);

    do something with mydisplay... 
}

So the the draw_display function is called by a interrupt from a microcontroller. In my ideal world, I would declare the mydisplay object somewhere global, setup the orientation and just use the global object in the function.

What would be the right c++ way to do this?

This is more of a "doing it the right way" and learn from it question.


Solution

  • my goal would be to call set_orientation only once.

    Then you can use an immediately-invoked lambda:

    static DISPLAY mydisplay = []{
    {
        DISPLAY ret(parameters);
        ret.set_orientation(0);
        return ret;
    }();