मैं बस की खोज की है std::shared_ptr
के "निर्माता अलियासिंग" और पाते हैं अपने आप पूछ "क्यों std नहीं है :: unique_ptr एक एक?std :: shared_ptr जैसे sti :: unique_ptr का कोई एलियासिंग कन्स्ट्रक्टर क्यों नहीं है?
यही है, अगर आप ऐसा कर सकते हैं कि एक Foo
आवंटित करना चाहते इसी राशि एक समारोह है कि पूरी तरह से Foo
के जीवनकाल का प्रबंधन करना चाहिए करने के लिए अपने Bar
सदस्य पारित यह अच्छा नहीं होगा ऐसा करने के लिए सक्षम होने के लिए?
#include <memory>
struct B {}
struct A {
B b;
}
void f(std::unique_ptr<B> b);
std::unique_ptr<A> a = std::make_unique<A>();
std::unique_ptr<B> b { std::move(a), &(a->b) }; // a now invalid.
f(std::move(b)); // f now responsible for deleting the A.
यह एसटीडी के साथ काम करता :: shared_ptr (http://ideone.com/pDK1bc)
#include <iostream>
#include <memory>
#include <string>
struct B {
std::string s;
};
struct A {
B b;
A(std::string s) : b{s} {};
~A() { std::cout << "A deleted." << std::endl; }
};
void f(std::shared_ptr<B> b) {
std::cout << "in f, b->s = " << b->s << " (use_count=" << b.use_count() << ")" << std::endl;
}
int main() {
std::shared_ptr<A> a = std::make_shared<A>("hello");
std::shared_ptr<B> b { a, &(a->b) };
a.reset(); // a now invalid.
std::cout << "before f, b->s = " << b->s << " (use_count=" << b.use_count() << ")" << std::endl;
f(std::move(b)); // f now responsible for deleting the A.
std::cout << "after f" << std::endl;
return 0;
}
उम्मीद outputs
before f, b->s = hello (use_count=1)
in f, b->s = hello (use_count=1)
A deleted.
after f
वहाँ एक तार्किक कारण है कि ऐसी बात शामिल नहीं किया गया है? और/या, को हटाए गए कस्टम डिलीटर के साथ unique_ptr<B>
के साथ अनुकरण करना एक बुरा विचार है?
और फिर जब डिलीटर के प्रकार का हिस्सा है, तो यह सादे 'unique_ptr 'के साथ अच्छी तरह से इंटरऑप नहीं करता है जब तक कि आप डिलीटर को मिटाने के प्रकार को टाइप न करें, जो कि अधिक अतिरिक्त ओवरहेड है। –
@ टी.सी .: यहां तक कि अगर आप डिलीटर मिटाते हैं, तो यह 'unique_ptr <टी, default_deleter>' के साथ अच्छी तरह से इंटरऑप नहीं करता है। कम से कम, केवल एक दिशा में रूपांतरण संभव है। –
@ बीन सिद्धांत में दोनों तरीकों से, जब तक विफलता की अनुमति है। – Yakk