shared_from_this

1、shared_from_this 是 C++11 标准库中提供的一个功能,它允许一个类生成指向其自身的 std::shared_ptr。这个功能主要通过继承 std::enable_shared_from_this 来实现。
2、shared_from_this 是 C++11 标准库中提供的一个功能,它允许一个类生成指向其自身的 std::shared_ptr。这个功能主要通过继承 std::enable_shared_from_this 来实现。为了使用 shared_from_this,类需要继承 std::enable_shared_from_this,并在需要生成 std::shared_ptr 的地方调用 shared_from_this。
3、代码示例

#include <iostream>
#include <memory>

class MyClass : public std::enable_shared_from_this<MyClass> {
public:
    void print() {
        std::shared_ptr<MyClass> p = shared_from_this();
        std::cout << "Shared pointer count: " << p.use_count() << std::endl;
    }
};

int main() {
    // 继承了enable_shared_from_this,最好代码中不要再使用裸指针
    std::shared_ptr<MyClass> obj = std::make_shared<MyClass>();
    obj->print();  // 调用 shared_from_this() 生成 shared_ptr
    return 0;
}

4、shared_from_this 的实现细节
std::enable_shared_from_this 类模板的内部实现非常巧妙,主要利用了 std::weak_ptr。以下是 std::enable_shared_from_this 的简化实现:

template <typename T>
class enable_shared_from_this {
protected:
    //enable_shared_from_this 的构造函数和赋值操作符被定义为 protected,以确保只有派生类可以调用。
    enable_shared_from_this() noexcept {}
    enable_shared_from_this(const enable_shared_from_this&) noexcept {}
    enable_shared_from_this& operator=(const enable_shared_from_this&) noexcept { return *this; }
    ~enable_shared_from_this() {}

public:
    // enable_shared_from_this 的构造函数和赋值操作符被定义为 protected,以确保只有派生类可以调用。
    std::shared_ptr<T> shared_from_this() {
        return std::shared_ptr<T>(weak_this_);
    }

    std::shared_ptr<const T> shared_from_this() const {
        return std::shared_ptr<const T>(weak_this_);
    }

    std::weak_ptr<T> weak_from_this() noexcept {
        return weak_this_;
    }

    std::weak_ptr<const T> weak_from_this() const noexcept {
        return weak_this_;
    }

private:
    // weak_this_ 是一个 std::weak_ptr,它保存了指向 shared_ptr 控制块的弱引用。通过 weak_this_ 可以安全地生成 shared_ptr。
    mutable std::weak_ptr<T> weak_this_;

    template <typename U>
    friend class std::shared_ptr;
};

namespace std {
    template<typename T>
    class shared_ptr {
    public:
        // shared_ptr 的构造函数负责在创建 shared_ptr 对象时,检查对象是否继承了 enable_shared_from_this,如果是,则将 weak_this_ 设置为指向当前的 shared_ptr
        template<typename U>
        explicit shared_ptr(U* ptr) {
            enable_shared_from_this<U>* esf = dynamic_cast<enable_shared_from_this<U>*>(ptr);
            if (esf) {
                esf->weak_this_ = *this;
            }
        }
    };
}

5、shared_from_this 是 C++11 标准库中一个非常有用的功能,它允许对象安全地生成指向自身的 std::shared_ptr。通过继承 std::enable_shared_from_this,类可以利用内部的 std::weak_ptr 来实现这一功能。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值