【发布时间】:2018-05-07 11:13:37
【问题描述】:
我尝试实现指向非指针的唯一指针,如下所述: 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:错误:'unsigned int'和'std::nullptr_t'类型的无效操作数到二进制'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)};
}
我做错了什么?
平台:Ubuntu 16.04
编译器:g++
【问题讨论】:
-
如果你只是注释掉
typedef会发生什么? -
编译器错误:Test.cpp:26:86:错误:没有匹配函数调用 'std::unique_ptr
::unique_ptr( ) ' -
是的,这就是我添加 typedef 的原因。根据链接的 SO question and article,如果您在删除器中使用 typedef 作为指针,您应该也可以将 unique_ptr 用于非指针类型。
-
文章似乎是错误的,如您链接的 SO 答案中所述。即使您在删除器中更改
T,它仍然必须满足 NullablePointer 概念,这就是为什么您的代码或文章will not work:您无法将GLuint与nullptr进行比较,这正是unique_ptr构造函数的作用。 -
最好将
GLuint包装到一个专用的包装器中,这样也可以防止混合不相关的值(例如GLuint用于着色器,GLuint用于缓冲区)。