指向非指针编译错误的唯一指针

Mic*_*ahn 3 c++ c++11 c++17

我尝试实现指向非指针的唯一指针,如下所述: One-liner for RAII on non pointer? https://dzone.com/articles/c11-smart-pointers-are-not。但我总是得到一个编译器错误:/usr/include/c++/5/bits/unique_ptr.h:235:12: error: invalid operands of types 'unsigned int' and 'std::nullptr_t' to binary 'operator!= '

这是我的代码:

struct ShaderDeleter
{
    typedef GLuint pointer; // Note the added typedef
    void operator()(GLuint shader) {
        glDeleteShader(shader);
    }
};

int main() {
    std::unique_ptr<GLuint, ShaderDeleter> smart_shader{glCreateShader(GL_VERTEX_SHADER)};
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

平台:Ubuntu 16.04

编译器:g++

M.M*_*M.M 5

根据 C++17 [unique.ptr.single]/3:

[...] 类型unique_ptr<T, D>::pointer应满足 的要求NullablePointer

这些要求可以在 [nullablepointer.semantics] 中找到,这里对其进行了总结。简而言之,该类型必须允许与nullptr. 所以不能使用整数作为类型。

您的非 SO 链接中的代码格式错误。SO链接中“fjoanis”的答案中的代码也是格式错误的。


相反,您可以使用其他解决方案之一来解决该问题。恕我直言unique_ptr不适合这项任务。有一个提案 P0052被称为std::unique_resource为此目的而设计的东西。

我可能会因为提到这一点而被否决,但也许您可以尝试使用void *作为指针类型,并将 GLuint 转换为void *. 一般来说,这样的转换是不可移植的,可能会导致运行时异常,但在常见的 x86 平台上,您可能会侥幸逃脱。链接到编译.