boost::shared_ptr mutual header inclusion problem

K

krema2ren

Hi

I've the following header problem that I need two classes to know each
other through a boost::shared_ptr. Does any of you smart guys have a
solution?

A.h
----------------------
#include "B.h"

Class A
{
public:
typedef boost::shared_ptr< A > SharedPtr;
void foo( B::SharedPtr& _b) {};
private:
B::SharedPtr b;

}

B.h
-------------------------
#include "A.h"

Class B
{
public:
typedef boost::shared_ptr< B > SharedPtr;
void foo( A::SharedPtr& _a) {};
private:
A::SharedPtr a;
}

Best Regards
Dennis Nielsen
 
A

Axter

krema2ren said:
Hi

I've the following header problem that I need two classes to know each
other through a boost::shared_ptr. Does any of you smart guys have a
solution?

A.h
----------------------
#include "B.h"

Class A
{
public:
typedef boost::shared_ptr< A > SharedPtr;
void foo( B::SharedPtr& _b) {};
private:
B::SharedPtr b;

}

B.h
-------------------------
#include "A.h"

Class B
{
public:
typedef boost::shared_ptr< B > SharedPtr;
void foo( A::SharedPtr& _a) {};
private:
A::SharedPtr a;
}

Don't use the typedef, and instead use forward class declaration, and
remove the #include

class A; //forward class declaration

class B
{
public:
void foo( boost::shared_ptr< A >& _a);// {};//Should move
implementation to source file for this method
private:
boost::shared_ptr< A > a;
};

FYI:
You should avoid using underscore prefix for your variable names,
because it can make your code non-portable. IAW C++ standard, variable
names that begin with an underscore are reserved for the
implementation.
 
E

Earl Purple

Axter said:
Don't use the typedef, and instead use forward class declaration, and
remove the #include

class A; //forward class declaration

class B
{
public:
void foo( boost::shared_ptr< A >& _a);// {};//Should move
implementation to source file for this method
private:
boost::shared_ptr< A > a;
};

You can also get around the problem by adding a fwd.h header for your
classes. You can also write your own forward class for boost
shared_ptr. Thus:

// boost_spfwd.h
namespace boost
{
template< typename T > shared_ptr;
tempalte < typename T > scoped_ptr;
}

..// afwd.h

#include boost_spfwd.h
class A;
typedef boost::shared_ptr< A > A_Ptr;
typedef boost::shared_ptr< const A > A_CPtr;
typedef boost::scoped_ptr< const A > A_ScopedPtr;

// etc and choose your own naming convention.

Of course it goes without saying you use all the correct file guards.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top