Forward declarations and shared_ptr

妖精的绣舞 提交于 2019-12-13 11:39:42

问题


I'm trying to refactor my code so that I use forward declarations instead of including lots of headers. I'm new to this and have a question regarding boost::shared_ptr.

Say I have the following interface:

#ifndef I_STARTER_H_
#define I_STARTER_H_

#include <boost/shared_ptr.hpp>

class IStarter
{
public:
    virtual ~IStarter() {};

    virtual operator()() = 0;
};

typedef boost::shared_ptr<IStarter> IStarterPtr;

#endif

I then have a function in another class which takes an IStarterPtr object as argument, say:

virtual void addStarter(IStarterPtr starter)
{
    _starter = starter;
}
...
IStarterPtr _starter;

how do I forward declare IStarterPtr without including IStarter.h?

I'm using C++98 if that is of relevance.


回答1:


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




回答2:


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.




回答3:


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.




回答4:


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;


来源:https://stackoverflow.com/questions/16588075/forward-declarations-and-shared-ptr

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