不能 return nullptr for unique_ptr return 类型

Can't return nullptr for unique_ptr return type

我正在为 SDL_Texture* 原始指针编写一个包装器,它 return 是 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 是可以接受的。我尝试在最后一个 return:

上传递一个空的 unique_ptr
return TexturePtr();

但在构建过程中出现类似错误。

请让我知道我做错了什么。

环境: 编译器:Visual C++ 14.1

unique_ptr(nullptr_t) 构造函数要求删除器是默认可构造的,并且它不是指针类型。您的删除器不满足第二个条件,因为删除器是指向函数的指针。参见 [unique.ptr.single.ctor]/1 and [unique.ptr.single.ctor]/4

此限制是一件好事,因为默认构建删除器会导致 nullptr 和未定义的行为,当您尝试调用删除器时,可能会导致段错误。

您可以将 return 语句更改为

return TexturePtr{nullptr, SDL_DestroyTexture};  // or just {nullptr, SDL_DestroyTexture}

或者,提供满足上述要求的删除器。我写的另一个答案中显示了一个这样的选项 here.