【发布时间】:2014-02-14 17:16:02
【问题描述】:
我有以下代码:
#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 为什么 Just Create One 击败了 Singleton。如果您只是使用全局变量,那么您已经完成了。
-
我尝试运行您的代码,但没有重复问题。
-
嗯。我正在使用 Visual Studio 2012(快捷版)。
-
我在 Redhat 上使用 G++ 4.8.1。
-
!instance和instance != nullptr之间是否存在隐含的等价关系?