Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward declarations and shared_ptr

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.

like image 819
Baz Avatar asked May 16 '13 12:05

Baz


People also ask

What is shared_ptr?

The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.

What does shared_ptr get () do?

A shared_ptr can share ownership of an object while storing a pointer to another object. This feature can be used to point to member objects while owning the object they belong to. The stored pointer is the one accessed by get(), the dereference and the comparison operators.

Can you forward declare Unique_ptr?

It's explicitly legal. The rule is that the types used to instantiate a template in the standard library must be complete, unless otherwise specified. In the case of unique_ptr , §20.7.

What is forward declaration C++?

Forward Declaration refers to the beforehand declaration of the syntax or signature of an identifier, variable, function, class, etc. prior to its usage (done later in the program). Example: // Forward Declaration of the sum() void sum(int, int); // Usage of the sum void sum(int a, int b) { // Body }


2 Answers

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

like image 77
jcoder Avatar answered Oct 06 '22 07:10

jcoder


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.

like image 40
JBL Avatar answered Oct 06 '22 08:10

JBL