首页 > 解决方案 > 将“this”传递给子对象

问题描述

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

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

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

class Parent
{
public:
    void MyMethod()
    {
        Child c;
        c.SetParent(this);
    }
};

标签: c++c++17

解决方案


std::weak_ptr<Parent>假设您正在使用C++11 后,您可以使用std::shared_ptr<Parent>(并继承自std::enable_shared_from_this以在内部生成 astd::shared_ptrstd::weak_ptr)。

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


推荐阅读