c++ - 无法为 unique_ptr 返回类型返回 nullptr

标签 c++ c++11 unique-ptr nullptr

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

相关文章:

c++ - 在 lambda 中使用模板参数

c++ - 为什么 setspacing 属性不起作用?

c++ - 使用邻接矩阵 C++ 实现图的深度优先遍历

c++ - 将 unique_ptr 插入 map ,指针被销毁

c++ - 在对象外部循环遍历 unique_ptr 集合

c++14 unique_ptr 并使 unique_ptr 错误使用已删除函数 'std::unique-ptr'

c++ - 指向指针的指针导致崩溃

c++ - 由于从 float 自动转换为 double,nan-boxing 的 std::num_put 问题

c++ - 在其命名空间之外定义的类成员函数

c++ - "error: use of deleted function"在 move 构造函数中对 unique_ptr 调用 std::move 时