将"this"传递给子对象

Passing `this` to child object

本文关键字:quot 对象 this      更新时间:2023-10-16

在使用C++17时,这种将this传递并存储到子对象的方法是否仍然被认为是"可接受的",或者是否有更合适的方法符合语言和标准?

我特别询问将Parent对象作为普通指针进行传递和存储的问题。

class Child
{
public:
void SetParent(Parent* p)
{
_parent = p;
}
private:
Parent* _parent;
};
class Parent
{
public:
void MyMethod()
{
Child c;
c.SetParent(this);
}
};

Post-C++11您可以使用std::weak_ptr<Parent>,假设您使用的是std::shared_ptr<Parent>(并从std::enable_shared_from_this继承以在内部生成std::shared_ptrstd::weak_ptr(。

除此之外,是的,使用原始指针来表示缺乏所有权或返回指针(直到委员会添加某种std::owned_ptr<T>/std::ptr_view<T>类(仍然是可以接受的。