dhe*_*har 7 c++ unique-ptr nullptr c++11
我正在为SDL_Texture*原始指针编写包装,该包装返回a 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;
}
Run Code Online (Sandbox Code Playgroud)
但是它给出了以下错误:
no suitable constructor exists to convert from "std::nullptr_t" to "std::unique_ptr<SDL_Texture, void (__cdecl *)(SDL_Texture *texture)>"
Run Code Online (Sandbox Code Playgroud)
根据我的理解,传递nullptr代替unique_ptr是可以接受的。我事件尝试在最后一次返回时传递一个空的unique_ptr:
return TexturePtr();
Run Code Online (Sandbox Code Playgroud)
但是在构建过程中得到类似的错误。
请让我知道我在做什么错。
Env:编译器:Visual C ++ 14.1
该unique_ptr(nullptr_t)构造要求删除器是缺省构造的,它不是一个指针类型。您的删除程序不满足第二个条件,因为删除程序是函数的指针。参见[unique.ptr.single.ctor] / 1和[unique.ptr.single.ctor] / 4。
这种限制是一件好事,因为nullptr在尝试调用删除程序时,默认构造删除程序会导致a 和不确定的行为,很可能导致段错误。
您可以将return语句更改为
return TexturePtr{nullptr, SDL_DestroyTexture}; // or just {nullptr, SDL_DestroyTexture}
Run Code Online (Sandbox Code Playgroud)
或者,提供满足上述要求的删除器。我在这里写的另一个答案中显示了这样一个选项。