Search code examples
c++sdl

In C++ can I pass a structure as a pointer without declaring it locally?


I'm working with SDL which is a C library that has declarations of functions like this:

void SDL_foo(SDL_Rect *rect);

I have my own wrappers around some of the functions like this:

void foo(SDL_Rect rect) {
  SDL_foo(&rect);
}

This is so I can simply call them like this:

foo({x, y, w, h});

My question is: is it possible to avoid having a wrapper function and do something like this:

SDL_foo(&{x, y, w, h});

Thanks!


Solution

  • No, you cannot do that because you can't get the address of a temporary.
    But you can probably get away with it with a kind of wrapper like this:

    struct MyRect {
        MyRect(SDL_rect rect): rect{rect} {}
        operator SDL_rect *() { return ▭ }
        SDL_rect rect;
    };
    
    SDL_foo(MyRect{{x, y, w, h}});
    

    Not tested yet, but it should give you an idea of what I mean.
    This way, instead of creating wrappers for all the functions from SDL, you have to create only a tiny wrapper around SDL_rect.
    Not sure if it works fine for you anyway.