Skip to content

Instantly share code, notes, and snippets.

@carun
Created November 20, 2012 11:35
Show Gist options
  • Save carun/4117423 to your computer and use it in GitHub Desktop.
Save carun/4117423 to your computer and use it in GitHub Desktop.
Singleton in a header only library
#include <iostream>
#include <stdint.h>
namespace Home { namespace Arun {
class Log
{
public:
static void Init(std::string& logPath, std::string& logFilename,
int32_t maxFileSize);
static Log* Instance();
static void Destroy();
private:
static Log* MyInstance(Log* pLog);
Log(std::string& logPath, std::string& logFilename, int32_t maxFileSize) :
m_logPath(logPath),
m_logFile(logFilename),
m_maxSize(maxFileSize)
{ }
~Log()
{ }
Log(const Log& log);
Log operator=(const Log& log);
std::string m_logPath;
std::string m_logFile;
int32_t m_maxSize;
};
inline void Log::Init(std::string& logPath, std::string& logFilename,
int32_t maxFileSize)
{
Log* ptr = new Log(logPath, logFilename, maxFileSize);
MyInstance(ptr);
}
inline Log* Log::Instance()
{
return MyInstance(NULL);
}
inline Log* Log::MyInstance(Log* ptr)
{
static Log* myInstance = NULL;
if (ptr)
myInstance = ptr;
return myInstance;
}
inline void Log::Destroy()
{
Log* pLog = MyInstance(NULL);
if (pLog)
delete pLog;
}
} }
#include "Log.hpp"
using namespace Home::Arun;
int main()
{
std::string logPath = ".";
std::string logFile = "Test.log";
Log::Init(logPath, logFile, 1024*1024);
Log* pLogInst = Log::Instance();
std::cout << pLogInst << std::endl;
Log::Destroy();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment