我正在为 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
最佳答案
unique_ptr(nullptr_t)
构造函数要求删除器是默认可构造的,并且它不是指针类型。您的删除器不满足第二个条件,因为删除器是指向函数的指针。参见 [unique.ptr.single.ctor]/1和 [unique.ptr.single.ctor]/4 .
此限制是一件好事,因为默认构造删除器会导致 nullptr
和未定义的行为,当您尝试调用删除器时,可能会导致段错误。
您可以将返回声明更改为
return TexturePtr{nullptr, SDL_DestroyTexture}; // or just {nullptr, SDL_DestroyTexture}
或者,提供满足上述要求的删除器。我写的另一个答案显示了一个这样的选项 here .
关于c++ - 无法为 unique_ptr 返回类型返回 nullptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56064769/