小编dhe*_*har的帖子

无法为unique_ptr返回类型返回nullptr

我正在为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

c++ unique-ptr nullptr c++11

7
推荐指数
1
解决办法
278
查看次数

标签 统计

c++ ×1

c++11 ×1

nullptr ×1

unique-ptr ×1