을 건설하고 난 다음 코드가 : 이것은 다음과 같은 출력싱글 두 번
을#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include <memory>
class Logger : public std::ofstream
{
public:
explicit Logger(std::string const& filename = "log.txt"):
std::ofstream(filename.c_str())
{
assert(*this);
*this << "-- log file start --\n" << std::endl;
}
Logger::~Logger()
{
*this << "\n-- log file end --" << std::endl;
this->close();
this->clear();
}
};
Logger logger;
template<class T>
class NotCopyable
{
public:
NotCopyable() { }
~NotCopyable() { }
private:
NotCopyable(NotCopyable const&);
NotCopyable const& operator=(NotCopyable const&);
};
template<class T>
class Singleton : public NotCopyable<Singleton<T> >
{
public:
static T& GetInstance()
{
if (!instance)
{
logger << "Initialize Singleton" << std::endl;
instance.reset(new T());
}
return *instance;
}
protected:
Singleton() { }
virtual ~Singleton() { }
private:
static std::unique_ptr<T> instance;
};
template<class T>
std::unique_ptr<T> Singleton<T>::instance;
class Factory : public Singleton<Factory>
{
public:
Factory() { logger << "Factory constructor" << std::endl; }
~Factory() { logger << "Factory destructor" << std::endl; }
void Blargl() { logger << "Blargl" << std::endl; }
};
bool DoStuff()
{
Factory::GetInstance().Blargl();
return true;
}
bool Thingy = DoStuff();
int main(int, char*[])
{
logger << "Start main()" << std::endl;
Factory::GetInstance().Blargl();
logger << "End main()" << std::endl;
}
:
-- log file start --
Initialize Singleton
Factory constructor
Blargl
Start main()
Initialize Singleton
Factory constructor
Blargl
End main()
Factory destructor
-- log file end --
내가 바보가 된 기분,하지만 공장은 두 번 대신에 건설되고있는 이유를 볼 수 없습니다 일단. 무슨 일 이니?
이유 # 57 왜 그냥 하나는 싱글의 지옥을 친다 만듭니다. 단순히 글로벌을 사용했다면 이미 끝났을 것입니다. – cHao
코드 실행을 시도했지만 문제가 중복되지 않았습니다. –
흠. Visual Studio 2012 (Express Edition)를 사용하고 있습니다. – user673679