My problem is straightforward: I am using SDL to create a simple simulation and I want to store instances of TTF_Font type in smart pointers (shared_ptr), but I keep getting this error:
"invalid application of ‘sizeof’ to incomplete type '_TTF_Font'"
Is there any way to use smart pointers with incomplete types from external libraries without incorporating their source code into my program?
EDIT:
TTF_Font is declared as
typedef struct _TTF_Font TTF_Font;
_TTF_Font is in turn defined in compiled external library.
My usage of TTF_Font is simply just constructing a new stack allocated instance of shared_ptr with a raw pointer to TTF_Font:
auto font_sp = std::shared_ptr<TTF_Font>(font_p);
I don't use sizeof explicitly here.
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.
this function is deprecated as of C++17 because use_count is only an approximation in multi-threaded environment.
The purpose of shared_ptr is to manage an object that no one "person" has the right or responsibility to delete, because there could be others sharing ownership. So you shouldn't ever want to, either.
The only difference between weak_ptr and shared_ptr is that the weak_ptr allows the reference counter object to be kept after the actual object was freed. As a result, if you keep a lot of shared_ptr in a std::set the actual objects will occupy a lot of memory if they are big enough.
Usually having a shared_ptr
of an incomplete type should work. You can declare a function like this
typedef struct _TTF_Font TTF_Font;
std::shared_ptr<TTF_Font> makeFont();
in a header file without problems. The implementation of makeFont()
will need to see the full definition of the class TTF_Font
though. Hence in the implementation file you will need to include the file which defines the TTF_Font
class. If you want to hide this implementation detail you may consider to put makeFont()
into a library which you include into you project. This way your project needs not to include the header files defining TTF_Font
unless you want to access members of this class for other reasons.
Concerning your Edit:
When you create a shared_ptr
from a pointer then the shared_ptr
will store internally how to delete that object. For this the shared_ptr
needs to see the destructor of the type pointed to. Therefore, shared_ptr
needs to see the struct definition even when no constructor is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With