shared_ptr with incomplete types from library

大城市里の小女人 提交于 2019-12-14 01:41:48

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/17649882/shared-ptr-with-incomplete-types-from-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!