簡體   English   中英

std :: enable_shared_from_this :: shared_from_this如何工作

[英]How std::enable_shared_from_this::shared_from_this works

我只是無法理解std::enable_shared_from_this::shared_from_this如何返回與現有指針共享所有權的共享pinter。 換句話說,你做這個

std::shared_ptr<Foo> getFoo() { return shared_from_this(); }

所以,當你打電話getFoo怎么不正是它得到的是對方shared_ptr分享與所有權,而不是創建一個單獨shared_ptr擁有相同this

我需要理解這一點,以便能夠理解如何從某個對象創建shared_ptr,這些對象都會增加相同的引用計數而不會初始化單獨的shared_ptr

enable_shared_from_this<T>有一個weak_ptr<T>數據成員。 shared_ptr<T>構造函數可以檢測T是否來自enable_shared_from_this<T> 如果是,則shared_ptr<T>構造函數將*this (這是shared_ptr<T> )分配給enable_shared_from_this<T>weak_ptr數據成員。 然后, shared_from_this()可以從weak_ptr<T>創建shared_ptr<T> weak_ptr<T>

可能的實現示例:

template<class D>
class enable_shared_from_this {
protected:
    constexpr enable_shared_from_this() { }
    enable_shared_from_this(enable_shared_from_this const&) { }
    enable_shared_from_this& operator=(enable_shared_from_this const&) {
        return *this;
    }

public:
    shared_ptr<T> shared_from_this() { return self_.lock(); }
    shared_ptr<T const> shared_from_this() const { return self_.lock(); }

private:
    weak_ptr<D> self_;

    friend shared_ptr<D>;
};

template<typename T>
shared_ptr<T>::shared_ptr(T* ptr) {
    // ...
    // Code that creates control block goes here.
    // ...

    // NOTE: This if check is pseudo-code. Won't compile. There's a few
    // issues not being taken in to account that would make this example
    // rather noisy.
    if (is_base_of<enable_shared_from_this<T>, T>::value) {
        enable_shared_from_this<T>& base = *ptr;
        base.self_ = *this;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM