Re: Global Dependencies Made Easy
Jason Hise wrote:
On Mar 31, 4:32 pm, Seungbeom Kim <musip...@bawi.org> wrote:
I think the article is easy to understand.
Let me give you some minor points.
class logger
{
private:
ofstream log;
logger() : log("log.txt") { }
Why is the constructor private? Since there's no friend, there's no way
to construct this object.
The constructor is private because this class is intended to be a
singleton. Other than the static instance declared in the instance
function, no instances should be able to be created.
Sorry for my silly mistake; I overlooked the whole purpose of the single
pattern. (Gee, wasn't I awake by that time?)
To make up for the mistake and add some new technical C++ content, let
me also suggest using a template class for the singleton pattern:
template <typename T>
class singleton
{
public:
static T& instance() { static T inst; return inst; }
protected:
singleton() { }
~singleton() { }
private: // not defined
singleton(const singleton&);
singleton& operator=(const singleton&);
};
class logger : private singleton<logger>
{
friend class singleton<logger>;
public:
using singleton<logger>::instance;
void log(const char* msg) { ofs << msg << std::endl; }
private:
logger() : ofs("log.txt") { }
std::ofstream ofs;
};
This looks like an overkill for such a simple singleton, but you can add
lots of details (e.g. multi-thread safety) to the singleton template,
which many other classes can reuse without clutters in their own code.
--
Seungbeom Kim
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]