我目前正在学习如何使用智能指针。然而在进行一些实验时,我发现了以下情况,但我找不到一个令人满意的解决方案:
假设你有一个A类对象作为一个B类对象(子对象)的父对象,但两者都应该相互知道:
class A;
class B;
class A
{
public:
void addChild(std::shared_ptr<B> child)
{
children->push_back(child);
// How to do pass the pointer correctly?
// child->setParent(this); // wrong
// ^^^^
}
private:
std::list<std::shared_ptr<B>> children;
};
class B
{
public:
setParent(std::shared_ptr<A> parent)
{
this->parent = parent;
};
private:
std::shared_ptr<A> parent;
};
这个问题是关于一个A类对象如何传递其自身(this
)的 std::shared_ptr
给它的子类。
有针对 Boost shared pointers 的解决方案(获取 boost::shared_ptr
以供使用),但如何使用 std::
智能指针来处理呢?