ファクトリクラスを実装しているうちに、私が理解できないような動作のあるstd::auto_ptr
が発生しました。問題を次の小さなプログラムに還元したので、始めましょう。シングルトンパターン:auto_ptrとunique_ptrの動作が異なります
次シングルトンクラスを考えてみましょう。ここでは、リソースを管理するスマートポインタの使用は、主によって決定される
#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.h 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;
}
面白い一部:私は、以下のプログラムでは、このコードを使用します。私は別に3つのソースをコンパイルします。
$ 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
私は別のコンパイラのブランド(IntelおよびGNU)とバージョンを試してみましたが、この動作は、それらの中で一貫しています。とにかく、私はリンクの順序に依存するコードを見ることができません。
さらに、auto_ptr
がunique_ptr
に置き換えられた場合、その動作は正しいものと常に一致します。
それは私に質問になります:ここで何が起こっているのか誰かが手がかりを持っていますか?
あなたのg ++バージョンは何ですか? –
あなたはおそらく[この質問](http://stackoverflow.com/questions/86582/)を読んでみたいです。 – fredoverflow