現在、スマートポインターの使用方法を学ぼうとしています。ただし、いくつかの実験を行っているときに、満足のいく解決策を見つけることができなかった次の状況を発見しました。
クラス 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;
};
std::shared_ptr
問題は、クラス A のオブジェクトがそれ自体 ( this
) をその子にどのように渡すことができるかということです。
Boost 共有ポインター ( for の取得boost::shared_ptr
this
std::
) の解決策はありますが、スマート ポインターを使用してこれを処理するにはどうすればよいでしょうか?