निम्न पर विचार करें:क्या मैं एक निजी कंस्ट्रक्टर के साथ boost :: make_shared का उपयोग कर सकता हूं?
class DirectoryIterator;
namespace detail {
class FileDataProxy;
class DirectoryIteratorImpl
{
friend class DirectoryIterator;
friend class FileDataProxy;
WIN32_FIND_DATAW currentData;
HANDLE hFind;
std::wstring root;
DirectoryIteratorImpl();
explicit DirectoryIteratorImpl(const std::wstring& pathSpec);
void increment();
bool equal(const DirectoryIteratorImpl& other) const;
public:
~DirectoryIteratorImpl() {};
};
class FileDataProxy //Serves as a proxy to the WIN32_FIND_DATA struture inside the iterator.
{
friend class DirectoryIterator;
boost::shared_ptr<DirectoryIteratorImpl> iteratorSource;
FileDataProxy(boost::shared_ptr<DirectoryIteratorImpl> parent) : iteratorSource(parent) {};
public:
std::wstring GetFolderPath() const {
return iteratorSource->root;
}
};
}
class DirectoryIterator : public boost::iterator_facade<DirectoryIterator, detail::FileDataProxy, std::input_iterator_tag>
{
friend class boost::iterator_core_access;
boost::shared_ptr<detail::DirectoryIteratorImpl> impl;
void increment() {
impl->increment();
};
bool equal(const DirectoryIterator& other) const {
return impl->equal(*other.impl);
};
detail::FileDataProxy dereference() const {
return detail::FileDataProxy(impl);
};
public:
DirectoryIterator() {
impl = boost::make_shared<detail::DirectoryIteratorImpl>();
};
};
ऐसा लगता है जैसे DirectoryIterator boost::make_shared<DirectoryIteratorImpl>
को कॉल करने में सक्षम होना चाहिए, क्योंकि यह DirectoryIteratorImpl
का मित्र है। हालांकि, यह कोड संकलित करने में विफल रहता है क्योंकि DirectoryIteratorImpl के लिए निर्माता निजी है।
चूंकि यह वर्ग एक आंतरिक कार्यान्वयन विस्तार है क्योंकि DirectoryIterator
के क्लाइंट कभी स्पर्श नहीं करना चाहिए, अगर मैं कन्स्ट्रक्टर को निजी रख सकता हूं तो यह अच्छा होगा।
क्या यह make_shared
के आसपास मेरी मूलभूत गलतफहमी है या क्या मुझे संकलित करने के लिए friend
के रूप में कुछ प्रकार के बूस्ट टुकड़े को चिह्नित करने की आवश्यकता है?
क्या आप वाकई अपने impl सूचक के लिए shared_ptr की आवश्यकता है? boost :: scoped_ptr आमतौर पर अधिक उपयुक्त है और चीजों को अधिक सरल बनाता है। Shared_ptr आमतौर पर केवल इस मामले में उपयोग किया जाएगा यदि आप निर्देशिकाइंटर को प्रतिलिपि बनाना चाहते थे और प्रतियों को एक एकल इंपोर्ट उदाहरण साझा करना चाहिए। आपके द्वारा पोस्ट किए गए कोड में, ऐसा लगता है कि एक इंपोर्ट साझा करने वाली प्रतियां एक त्रुटि होगी। Shared_ptr तब होता है जब एकाधिक पॉइंटर्स को किसी उदाहरण के स्वामित्व को साझा करना चाहिए। – Alan