Shared_ptr with incomplete types from the library

My problem is simple: I use SDL to create a simple simulation, and I want to store instances of type TTF_Font in smart pointers (shared_ptr), but I keep getting this error:

"incorrectly applying the sizeof parameter to the incomplete type _TTF_Font '"

Is there a way to use smart pointers with incomplete types from external libraries without including their source code in my program?

EDIT:

TTF_Font is declared as

typedef struct _TTF_Font TTF_Font; 

_TTF_Font, in turn, is defined in the compiled external library.

My use of TTF_Font is simply to create a new instance with the shared_ptr stack allocated, with a raw pointer to TTF_Font :

 auto font_sp = std::shared_ptr<TTF_Font>(font_p); 

I do not use explicitly sizeof here.

+2
source share
1 answer

Generally, having an incomplete shared_ptr should work. You can declare such a function

 typedef struct _TTF_Font TTF_Font; std::shared_ptr<TTF_Font> makeFont(); 

in the header file no problem. However, the implementation of makeFont() should see the full definition of the TTF_Font class. Therefore, in the implementation file, you will need to specify the file that defines the TTF_Font class. If you want to hide this implementation detail, you might consider putting makeFont() in the library that you included in the project. Thus, your project should not include header files defining TTF_Font unless you want to access members of this class for other reasons.

Regarding your Edit:

When you create shared_ptr from a pointer, then shared_ptr will store inside itself how to delete this object. For this, shared_ptr should see a destructor of the specified type. Therefore, shared_ptr should see the definition of the structure even when the constructor is called.

+5
source

Source: https://habr.com/ru/post/957625/


All Articles