将 unique_ptr 与 GLFWwindow 一起使用

use unique_ptr with GLFWwindow

我正在使用 GLFW 处理应用程序中的 window 事件。它工作正常。后来我决定删除从 GLFWwindow 开始的原始指针。它在文件 glfw3.h 中定义为:

typedef struct GLFWwindow GLFWwindow; 

而且我在头文件中找不到结构的实际定义。所以我认为这是一种前向声明,但我不知道为什么它不像

struct GLWwindow;

我尝试用前向声明的后一种形式来代替前一种形式。它编译得很好。前阵型前向申报的优点是什么?

所以真正的问题,由于结构GLFWwindow只是一个声明,没有定义的唯一指针不能完成模板特化。我不能使用 unique_ptr 来声明任何指针。编译器给我错误

C2027 use of undefined type 'GLFWwindow'
C2338 can't delete an incomplete type
C4150 deletion of pointer to incomplete type 'GLFWwindow';no destructor called

有人知道如何在 GLFW 中使用唯一指针window吗?

谢谢

您需要将删除器提供给唯一的指针:

struct DestroyglfwWin{

    void operator()(GLFWwindow* ptr){
         glfwDestroyWindow(ptr);
    }

}

std::unique_ptr<GLFWwindow, DestroyglfwWin> my_window;

使用类型定义的智能指针会很方便。

typedef std::unique_ptr<GLFWwindow, DestroyglfwWin> smart_GLFWwindow;

smart_GLFWwindow my_window;

but I have no idea why it is not like …

那是因为 GLFW 是用 C 而不是 C++ 编写的。这两种语言是完全不同的语言,其中 声明 工作有一些重叠,但即使如此也存在重大差异,如您所见。

在 C structs 和 enums 中每个都存在于自己的 tag 命名空间中,你必须明确地写 struct name_of_the_struct …enum name_of_the_enum … 来使用它。通过声明此类型定义 typedef struct … …,您将结构拉入常规变量和类型命名空间。有铁杆 C 程序员(包括我)认为,不应该这样做。如果你在写 C++,你就是在写 C++,如果你在写 C,你就是在写 C,没有混淆这两者的危险。

What is the pro of the former formation of forward declaration?

在编写 C 语言时节省了几次击键。就是这样…

So the real questions, since the structure GLFWwindow is only a declaration, unique pointer can not complete template specialization without definition. I can not use unique_ptr to declare any pointer.

unique_ptr 不仅仅是结构定义。 A unique_ptr(我强调):

std::unique_ptr is a smart pointer that retains sole ownership of an object through a pointer and destroys that object when the unique_ptr goes out of scope. No two unique_ptr instances can manage the same object.

通过对对象调用 delete 来进行销毁,这又会调用析构函数。在 C++ 中,struct 实际上都是默认的 public class,因此 constructor/destructor 语义按预期工作。但在普通 C 中,结构只是普通内存。所以 unique_ptr 的语义并不真正适用。您需要一些助手 class,它可以增强 constructor/destructor 语义。请参阅 ratchet_freak 的回答。