2015-12-03 10 views
10

मैं समझ नहीं पा रहा हूं कि कैसे std::enable_shared_from_this::shared_from_this एक साझा पिनटर देता है जो मौजूदा पॉइंटर के साथ स्वामित्व साझा करता है। दूसरे शब्दों में आप this कार्य करें:कैसे std :: enable_shared_from_this :: shared_from_this काम करता है

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

तो जब आप getFoo फोन कैसे वास्तव में इसके साथ स्वामित्व साझा करने के अन्य shared_ptr है और एक अलग shared_ptr है कि एक ही this का मालिक बनाने के लिए नहीं क्या मिलता है।

मुझे समझने में सक्षम होने के लिए यह समझने में सक्षम होना चाहिए कि कुछ ऑब्जेक्ट से shared_ptr कैसे बनाया जाए, जो सभी एक ही रेफ गिनती को बढ़ाते हैं और अलग shared_ptr एस प्रारंभ नहीं करते हैं।

+2

http://en.cppreference.com/w/cpp/memory/enable_shared_from_this नोटों – StoryTeller

+0

मैं नोट्स सामान्य कार्यान्वयन का वर्णन है कि देखा है पर एक नज़र डालें । इससे पहले, मैंने भी सोर्स कोड को देखा है। लेकिन यह समझ में नहीं आया कि इस 'weak_ptr' को प्रारंभ किया जा रहा है जब पहली साझा_प्टर कक्षा के बाहर बनाया गया है। एक वर्ग यह नहीं जान सकता कि हमने कुछ 'shared_ptr' में अपने सूचक को encapsulated किया है। – Narek

+2

आपको 'std :: shared_ptr' के स्रोत पर भी एक नज़र डालना चाहिए। नोट स्पष्ट रूप से निर्दिष्ट करता है कि वहां बेस कोड के रूप में 'std :: enable_shared_from_this' की उपस्थिति का पता लगाने के लिए कोड है। – StoryTeller

उत्तर

16

enable_shared_from_this<T> में weak_ptr<T> डेटा सदस्य है। shared_ptr<T> कन्स्ट्रक्टर पता लगा सकता है कि Tenable_shared_from_this<T> से लिया गया है। अगर ऐसा है, shared_ptr<T> निर्माता enable_shared_from_this<T> में weak_ptr डेटा सदस्य को *this प्रदान करेंगे (जो shared_ptr<T> है)। shared_from_this()weak_ptr<T> से shared_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; 
    } 
} 
+0

'enable_shr_thom_this' के' shared_ptr' को 'weak_ptr' सदस्य तक पहुंच है (मुझे लगता है कि यह निजी है)। – Narek

+3

@Narek यह शायद एक 'दोस्त' है। – Simple

+0

सी ++ 17 में, आप 'if' चेक (जो वर्तमान में * छद्म कोड *) संकलित-समय शाखा का उपयोग करके संकलित कर सकते हैं: 'if constexpr (...) {...}' – Nawaz

संबंधित मुद्दे