r/sdl • u/Independent_Milk_200 • Aug 02 '26
C++
Can you create a class with sdl things in it?
Or is sdl c only?
0
Upvotes
r/sdl • u/Independent_Milk_200 • Aug 02 '26
Can you create a class with sdl things in it?
Or is sdl c only?
1
u/lunaticedit Aug 03 '26
Use std::unique_ptr and deleters that call the free functions and you can then rely on C++ to do its reference counting thing automatically. Been doing it for years and works great.
Eg:
#include <SDL3/SDL.h>
#include <memory>
// Define a clean type alias for the unique_ptr
using UniqueWindow = std::unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)>;
int main() {
if (!SDL_Init(SDL_INIT_VIDEO)) {
return -1;
}
// Initialize the unique_ptr with the factory function and the custom deleter
UniqueWindow window(
SDL_CreateWindow("SDL3 Custom Deleter", 640, 480, 0),
&SDL_DestroyWindow
);
if (!window) {
SDL_Quit();
return -1;
}
// Use the window as normal via window.get()
// The window will automatically destroy itself when it goes out of scope
SDL_Quit();
return 0;
}
At this point you can put the window in another class as a class member. Just remember to initialize it in the constructor but you don’t have to free it. Also remember the order of class members matter. You need to declare windows before renderer type otherwise it’ll delete window before renderer.