【发布时间】:2023-04-03 03:26:01
【问题描述】:
我正在为SDL_Texture* 原始指针编写一个包装器,它返回一个unique_ptr。
using TexturePtr = std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)>;
TexturePtr loadTexture(SDL_Renderer* renderer, const std::string &path) {
ImagePtr surface =
loadImage(path);
if (surface) {
return TexturePtr(
SDL_CreateTextureFromSurface(renderer, surface.get())
, SDL_DestroyTexture);
}
return nullptr;
}
但它给出了以下错误:
no suitable constructor exists to convert from "std::nullptr_t" to "std::unique_ptr<SDL_Texture, void (__cdecl *)(SDL_Texture *texture)>"
根据我的理解,通过 nullptr 代替 unique_ptr 是可以接受的。我尝试在最后一次返回时传递一个空的 unique_ptr:
return TexturePtr();
但在构建过程中出现类似错误。
请让我知道我在这里做错了什么。
环境: 编译器:Visual C++ 14.1
【问题讨论】:
-
编译器应该如何确定您要使用的删除器?当删除器是指向函数的指针时,采用
nullptr_t的unique_ptr构造函数会被 SFINAE 淘汰。 -
最好有专用的删除器,而不是在函数上使用指针。 (这将解决你的问题顺便说一句:))
标签: c++ c++11 unique-ptr nullptr