Returnshared_ptr交给SDL_GL_SwapWindow

Return shared_ptr and hand it over to SDL_GL_SwapWindow

因为我需要在不同的 classes 中指向 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)).

总的来说,只要它们在同一个 class 中,用 .get() 移交指向 SDL 函数的指针似乎是可行的:SDL_GL_CreateContext(shared_Window_A.get()) 似乎可行/不提高编译器A::foo().

中的错误

现在我被卡住了,想保留 shared_ptr 而不是原始指针,因为它似乎对其他人有用。所以我假设我只是在将 shared_ptr 从 class A 移交给 class B 时做错了。但是搜索 returning a shared pointer 结果证明我的尝试看起来并没有那么错.

那么我如何以与 SDL2 一起工作的方式将 shared_ptr 从一个 class 移交给另一个?

您不能只传递指向 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);