Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use unique_ptr with GLFWwindow

Tags:

c++

opengl

glfw

I am using GLFW for handling window events in an application. It works fine. Later I decide to remove raw pointers starting from GLFWwindow. It defined in the file glfw3.h as:

typedef struct GLFWwindow GLFWwindow; 

And I cannot find the actual definition of the structure in the header file. So I assume this is a kind of forward declaration, but I have no idea why it is not like

struct GLWwindow;

I tried to use the later form of forward declaration to replace the former form. It compiles fine. What is the pro of the former formation of forward declaration?

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. The compiler gives me error

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

Anyone knows how to use unique pointer with GLFWwindow?

Thanks

like image 835
r0n9 Avatar asked Mar 04 '16 10:03

r0n9


People also ask

When should we use unique_ptr?

Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.

What happens when unique_ptr goes out of scope?

unique_ptr. An​ unique_ptr has exclusive ownership of the object it points to and ​will destroy the object when the pointer goes out of scope.

How is unique_ptr implemented in C++?

unique_ptr allows only one owner of the underlying pointer while shared_ptr is a reference-counted smart pointer. In this implementation, the developer doesn't need to explicitly delete the allocated memory towards the end of the function.


1 Answers

You'll need to supply the Deleter to the unique ptr:

struct DestroyglfwWin{

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

}

std::unique_ptr<GLFWwindow, DestroyglfwWin> my_window;

It can be handy to use a typedefed smart pointer.

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

smart_GLFWwindow my_window;
like image 151
ratchet freak Avatar answered Oct 28 '22 17:10

ratchet freak