Ashley Ashley - 3 months ago 20
C++ Question

Shared pointer only initialising via std::shared_ptr. The std::make_shared constructor is not working

I am making a basic game using SDL2 and C++. I have been slowly changing my bad use of raw pointers to safer smart pointers.

The

_window
variable is a private class member:

private:
std::shared_ptr<SDL_Window> _window;


The following code works:

_window = std::shared_ptr<SDL_Window>(SDL_CreateWindow(
"Game",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH,
SCREEN_HEIGHT,
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE
));


The following code does not work:

_window = std::make_shared<SDL_Window>(SDL_CreateWindow(
"Game",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH,
SCREEN_HEIGHT,
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE
));


The following error is thrown:

C:\...\include\type_traits(984): error C2027: use of undefined type 'SDL_Window'


This is very confusing, because
type_traits
is part of the standard library. I am therefore not sure where the source of the error is, but it is not viable to include my entire project here.

What could be causing such an error to be thrown, simply by changing
std::shared_ptr
to
std::make_shared
?

Answer

make_shared is for creating a new object, not for assuming ownership of an existing one.
The function constructs the object itself, so it needs the class definition.

("Make shared" doesn't mean "make this pointer shared", but "make an object that can be shared". It's the "make" of "make me a pizza", not of "make me a rockstar" - that is, creation, not transformation.)

You can't use make_shared here since the only way to create a SDL_Window is through SDL_CreateWindow.
(And there would be no point since the window already exists.)

You also need to pass a custom deletion function to the constructor, since SDL requires a specific function to destroy the window:

_window = std::shared_ptr<SDL_Window>(SDL_CreateWindow("Game", ...), SDL_DestroyWindow);