Creating a pointer to an SDL_Window struct and assigning it to a shared_ptr, the mentioned error results.
Part of the class:
#include <SDL2/SDL.h>
class Application {
static std::shared_ptr<SDL_Window> window;
}
Definition:
#include "Application.h"
std::shared_ptr<SDL_Window> Application::window{};
bool Application::init() {
SDL_Window *window_ = nullptr;
if((window_ = SDL_CreateWindow(title.c_str(),
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
window_width,
window_height,
NULL)
) == nullptr) {
std::cerr << "creating window failed: " << SDL_GetError() << std::endl;
}
window.reset(window_);
}
The error appears at 'window.reset()'. What is the reason and how to fix this behavior?
By default, shared_ptr
will release the managed resource using delete
. However, if you're using a resource that needs releasing another way, you'll need a custom deleter:
window.reset(window_, SDL_DestroyWindow);
NOTE: I'm fairly sure this will work, but I don't have an SDL installation to test it with.
As said previously by Mike, you'll have to specify your deleter with shared_ptr
. For a unique_ptr
, however, you'll probably want to create a special type for your deleter so that it can be cleanly used as a template parameter. I used this struct:
struct SDLWindowDeleter {
inline void operator()(SDL_Window* window) {
SDL_DestroyWindow(window);
}
};
Then include the deleter via template parameter:
std::unique_ptr<SDL_Window, SDLWindowDeleter> sdlWindowPtr = SDL_CreateWindow(...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With