与共享指针的循环依赖

时间:2012-05-15 19:23:43

标签: c++ shared-ptr circular-dependency

我在程序中遇到了循环依赖,并使用指针和前向声明解决了它。我为此目的制作了一个文件dn.hpp。一切都很好,直到我转移到共享指针而不是泛型。我在dn.hpp中为共享指针创建了typedef。一切都适用于通用指针(注释掉),发髻不是共享。

它返回一个错误: 字段'parentGraph'具有不完整类型node.h第21行

(我正在使用mingw with boost 1.47)

请帮我解决此问题。

以下是我的代码的简化版本:

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;
}

1 个答案:

答案 0 :(得分:2)

当我使用VisualStudio编译代码时,我得到了

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

添加

#include <boost/weak_ptr.hpp>

解决了这个问题