Yuriy Petrovskiy
Yuriy Petrovskiy

Reputation: 8188

Circular dependency with shared pointers

I had faced a circular dependency in my program and solved it with using pointers and forward declarations. I had made a file dn.hpp for this purpose. Everything was OK until I moved to shared pointers instead of generic. I created typedefs for shared pointers in dn.hpp. Everything works with generic pointers (commented out), bun not with shared.

It returns an error: field 'parentGraph' has incomplete type node.h line 21

(I am using mingw with boost 1.47)

Please help me to resolve this issue.

Here is simplified version of my code:

dn.hpp

// forward declarations
#include <map>
#include <list>
#include <boost/shared_ptr.hpp>

class graph;
typedef boost::weak_ptr<graph> graph_wp;
typedef boost::shared_ptr<graph> graph_sp;
//typedef graph* graph_wp;
//typedef graph* graph_sp;

class node;
typedef boost::weak_ptr<node> node_wp;
typedef boost::shared_ptr<node> node_sp;
//typedef node* node_wp;
//typedef node* node_sp;
typedef std::list<node_sp> nodes_t;

class edge;
typedef boost::weak_ptr<edge> edge_wp;
typedef boost::shared_ptr<edge> edge_sp;
//typedef edge* edge_wp;
//typedef edge* edge_sp;
typedef std::list<edge_sp> edges_t;
typedef std::list<edge_wp> edgeList_t;

graph.h

#ifndef GRAPH_H_
#define GRAPH_H_

#include "node.h"
#include "edge.h"

#include "dn.hpp"

class graph
{
public:
    node* createNode();
protected:
    nodes_t nodes;
    edges_t edges;
};
#endif /*GRAPH_H_ */

node.h

#ifndef NODE_H_
#define NODE_H_

#include "graph.h"
#include "edge.h"

#include "dn.hpp"

class node
{
public:
    node();
    node(graph_wp n);
    node(const graph_wp& net);
    virtual ~node();

    edge_wp createChild();
protected:
    graph_wp parentGraph;
    edgeList_t edges;
};
#endif /* NODE_H_ */

edge.h

#ifndef EDGE_H_
#define EDGE_H_

#include "node.h"

#include "dn.hpp"

class edge
{
public:
    edge(node_wp src,node_wp tgt);
    virtual ~edge();
private:
    node_sp source;
    node_sp target;
};
#endif /* EDGE_H_ */

main.cpp

#include "graph.h"
int main() {
    graph n;
    return 0;
}

Upvotes: 3

Views: 1254

Answers (1)

Stephen Nutt
Stephen Nutt

Reputation: 3306

When I compile your code with VisualStudio I get

error C2079: 'node::parentGraph' uses undefined class 'boost::weak_ptr<Y>'
with
[
    Y=graph
]

Adding

#include <boost/weak_ptr.hpp>

fixes this

Upvotes: 2

Related Questions