实际编程中有时会碰到两个类之间交叉引用的问题,比如一个类A含一个类B的指针成员,一个类B含类A的指针成员,两个类相互“关联”;而且更重要的是:对类B的任意修改应该同时改变A中的B指针指向的值,同理适用于类A。良好的设计应当可以通过任意一个类的接口来同时改变A、B两个对象,而不必调用两个类的对应接口。
boost::enable_shared_from_this提供了这个能力
代码:
A.h:
#pragma once
#include <boost/shared_ptr.hpp>
class CB;
typedef boost::shared_ptr<CB> B_ptr;
class CA
{
friend class CB; // 为了调用SetB函数
public:
CA(int i):m_aInt(i){}
B_ptr GetB(){ return m_bObj; }
void SetI(int i){ m_aInt = i; }
int GetI(){ return m_aInt; }
private:
// 为了防止此接口误用,让其为private
// 改变关联时应通过B的接口,否则造成"a关联了b,但b没有关联a"
void SetB(B_ptr pb) { m_bObj = pb; } // 这个函数只在B中关联时被调用
int m_aInt;
B_ptr m_bObj;
};
typedef boost::shared_ptr<CA> A_ptr;
B.h:
#pragma once
#include <boost/enable_shared_from_this.