Forward declarations and shared_ptr

别等时光非礼了梦想. 提交于 2019-12-03 12:25:43

Shared pointers work with forward declared types as long as you dont call * or -> on them so it should work to simply write :-

class IStarter;
typedef boost::shared_ptr<IStarter> IStarterPtr;

You need to include <boost/shared_ptr.hpp> of course

Though it would add a header file, you could put that in a separate header file :

#include <boost/shared_ptr.hpp>

class IStarter;
typedef boost::shared_ptr<IStarter> IStarterPtr;

and then include it both in IStarter.h and in your other header, avoiding code duplication (though it's quite small in this case).

There might be better solutions though.

You can't forward declare typedefs in C++98 so what I usually do in this case is pull out the typedefs I need an put them into a types.h file, or something similar. That way the common type code is still separated from the definition of the class itself.

There is a way but you need to include the boost header in your file :

#include <boost/shared_ptr.hpp>

class IStarter;
typedef boost::shared_ptr<IStarter> IStarterPtr;

// ...

virtual void addStarter(IStarterPtr starter)
{
      _starter = starter;
}
// ...
IStarterPtr _starter;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!