का एक अलग व्यवहार कारखाने वर्ग को लागू करते समय मुझे std::auto_ptr
का एक व्यवहार सामना करना पड़ा जिसे मैं समझ नहीं पा रहा हूं। मैंने समस्या को निम्न छोटे प्रोग्राम में कम कर दिया, तो ... चलो शुरू करें।सिंगलटन पैटर्न: auto_ptr और unique_ptr
निम्नलिखित सिंगलटन वर्ग पर विचार करें:
singleton.h
#ifndef SINGLETON_H_
#define SINGLETON_H_
#include<iostream>
#include<memory>
class singleton {
public:
static singleton* get() {
std::cout << "singleton::get()" << std::endl;
if (!ptr_.get()) {
std::cout << &ptr_ << std::endl;
ptr_.reset(new singleton );
std::cout << "CREATED" << std::endl;
}
return ptr_.get();
}
~singleton(){
std::cout << "DELETED" << std::endl;
}
private:
singleton() {}
singleton(const singleton&){}
static std::auto_ptr<singleton> ptr_;
//static std::unique_ptr<singleton> ptr_;
};
#endif
singleton.cpp
#include<singleton.h>o
std::auto_ptr<singleton> singleton::ptr_(0);
//std::unique_ptr<singleton> singleton::ptr_;
यहाँ एक स्मार्ट सूचक के उपयोग के संसाधन का प्रबंधन करने में मुख्य रूप से से निर्धारित होता कार्यक्रम से बाहर निकलने पर लीक से बचने की जरूरत है।
a.h
#ifndef A_H_
#define A_H_
int foo();
#endif
a.cpp
#include<singleton.h>
namespace {
singleton * dummy(singleton::get());
}
int foo() {
singleton * pt = singleton::get();
return 0;
}
main.cpp
#include<a.h>
int main() {
int a = foo();
return 0;
}
अब अजीब हिस्सा: मैं उसके बाद निम्न कार्यक्रम में इस कोड का उपयोग करें। मैं अलग से तीन स्रोतों संकलन:
$ g++ -I./ singleton.cpp -c
$ g++ -I./ a.cpp -c
$ g++ -I./ main.cpp -c
अगर मैं उन्हें स्पष्ट रूप से जोड़ने के इस क्रम में: के रूप में मैं उम्मीद
$ g++ main.o singleton.o a.o
सब कुछ काम करते हैं, और मैं stdout में निम्नलिखित हो:
singleton::get()
0x804a0d4
CREATED
singleton::get()
DELETED
यदि इसके बजाय मैं इस आदेश का उपयोग कर स्रोतों को लिंक करता हूं:
$ g++ a.o main.o singleton.o
मैं इस उत्पादन प्राप्त करें:
singleton::get()
0x804a0dc
CREATED
singleton::get()
0x804a0dc
CREATED
DELETED
मैं अलग संकलक ब्रांडों (इंटेल और GNU) और संस्करणों की कोशिश की और इस व्यवहार उन के बीच में संगत है। वैसे भी, मैं कोड नहीं देख पा रहा हूं जिसका व्यवहार लिंकिंग के क्रम पर निर्भर करता है।
इसके अलावा, auto_ptr
unique_ptr
द्वारा प्रतिस्थापित किया गया है, व्यवहार हमेशा एक सही होने की अपेक्षा के अनुरूप है।
यह मुझे प्रश्न पर लाता है: क्या किसी के पास क्या हो रहा है इस पर कोई संकेत है?
आपका जी ++ संस्करण क्या है? –
शायद आप [इस सवाल] को पढ़ना चाहते हैं (http://stackoverflow.com/questions/86582/)। स्पष्टीकरण के लिए – fredoverflow