我正在尝试研究如何将 std::shared_ptr 与自定义删除器一起使用。具体来说,我将它与 SDL_Surface 一起使用:
std::shared_ptr<SDL_Surface>(SDL_LoadBMP(....),SDL_FreeSurface);
编译和运行良好。但是,我想尝试自己的删除器,但不知道该怎么做。 SDL_FreeSurface 的文档可在此处找到:
http://sdl.beuc.net/sdl.wiki/SDL_FreeSurface
我在其中发现 SDL_FreeSurface 声明为:
void SDL_FreeSurface(SDL_Surface* surface);
作为测试,根据该信息,我尝试了以下功能:
void DeleteSurface(SDL_Surface* surface)
{
std::cout << "Deleting surface\n";
SDL_FreeSurface(surface);
}
但是,使用 g++ 编译会出现以下错误:
error: no matching function for call to 'std::shared_ptr<SDL_Surface>::shared_ptr(SDL_Surface*, <unresolved overloaded function type>)'
我查看了 gcc std::shared_ptr 实现的 gnu 文档,但无法理解它。我做错了什么?
编辑:我已经缩小了问题的范围,但会留下上面的原始问题。我所拥有的是一个 Game 类,如果我将其分解为基本实现,则类似于:
class Game {
public:
/* various functions */
private:
void DeleteSurface(SDL_Surface* surface);
bool CacheImages();
std::vector<std::shared_ptr<SDL_Surface> > mCachedImages;
/* various member variables and other functions */
}
DeleteSurface
的实现如上,CacheImages()
的实现如:
bool CacheImages()
{
mCachedImages.push_back(std::shared_ptr<SDL_Surface>(SDL_LoadBMP(...),DeleteSurface);
return true;
}
我上面列出的错误是哪个游戏我。但是,如果我将 DeleteSurface()
函数移到 Game
类之外而不进行其他更改,则代码会编译。在 Game
类中包含 DeleteSurface
函数会导致什么问题?
最佳答案
std::shared_ptr<SDL_Surface>(SDL_LoadBMP(....), [=](SDL_Surface* surface)
{
std::cout << "Deleting surface\n";
SDL_FreeSurface(surface);
});
或
void DeleteSurface(SDL_Surface* surface)
{
std::cout << "Deleting surface\n";
SDL_FreeSurface(surface);
}
std::shared_ptr<SDL_Surface>(SDL_LoadBMP(....), DeleteSurface);
编辑:
看到你更新的问题,DeleteSurface
应该是非成员函数,否则需要使用std::bind
或者std::mem_fn
或其他一些成员函数指针适配器。
关于c++ - 使用成员函数作为自定义删除器与 std::shared_ptr 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12340810/