返回shared_ptr并将其交给SDL_GL_SwapWindow

时间:2018-01-30 17:42:36

标签: c++ shared-ptr sdl-2

由于我需要在不同类中使用指向SDL_Window的指针,我认为使用shared_ptr是个好主意。

//happens in class A::foo()
//shared_Window_A is of type std::shared_ptr<SDL_Window>

shared_Window_A = std::make_shared<SDL_Window>(SDL_CreateWindow(..), SDL_DestroyWindow); 
GLContext = SDL_GL_CreateContext(shared_Window_A.get()) //no compiler-error here

//Hand-over function of class A 
std::shared_ptr<SDL_Window> GetWindow(){return shared_Window_A;);

//happens in class B::bar()
//shared_Window_B is of type std::shared_ptr<SDL_Window>

shared_Window_B = A.GetWindow();
SDL_GL_SwapWindow(shared_Window_B.get()); 
//gives "undefined reference to SDL_GL_SwapWindow"

SDL_GL_SwapWindowSDL_GL_CreateContext都需要SDL_Window* window

虽然我显然还在了解shared_ptrs,但我真的不知道这里出了什么问题。我也尝试了更丑陋的(&(*shared_Window_B))

总的来说,只要它们在同一个类中,就可以将指针切换到带有.get()的SDL函数:SDL_GL_CreateContext(shared_Window_A.get())似乎在A::foo()中工作/不会引发编译器错误}。

现在我陷入困境,希望保留shared_ptr而不是原始指针,因为它似乎适用于其他人。所以我假设我在将shared_ptr从A类移交给B类时做错了。但是搜索returning a shared pointer结果证明我的尝试看起来并没有错。

那么如何以与SDL2一起使用的方式将shared_ptr从一个类移交给另一个类呢?

1 个答案:

答案 0 :(得分:3)

您无法传递指向std::make_shared的指针。如果框架创建了对象,那么您必须避免std::make_shared。也许这对你有用:

// shared_Window_A is of type std::shared_ptr<SDL_Window>

auto win = SDL_CreateWindow(..); // get the pointer from the framework

// now pass it in to the shared pointer to manage its lifetime:
shared_Window_A = std::shared_ptr<SDL_Window>(win, SDL_DestroyWindow); 

或简洁地说:

shared_Window_A = std::shared_ptr<SDL_Window>(SDL_CreateWindow(..), SDL_DestroyWindow);