Pe*******@gmail.com wrote:
Hi,
I want to define an unique file object, like cout, where there is the
only such one in the program.
It seems that singleton pattern can be used for this purpose. But I'm
wondering if cout is an singleton. I would guess not. There were some
threads in the newsgroup discuss about cout and singleton, which is
too long for me to catch the main point. Can somebody give me a brief
introduction on this? And show me how to define an global file object?
.....
// public header file myiostream.h
#include <iostream>
namespace MYSPACE
{
extern std::ostream & MYOSTREAM;
} // end namespace
.....
.....
// implementation file - myiostream.cpp
#include "myiostream.h"
#include <fstream>
namespace { // anon namespace
struct my_fstream : std::fostream
{
std::fostream m_fostream;
my_fstream()
: m_fostream( "file name" );
{
// do whatever you want to open the file before main()
// is called here
}
};
my_fstream s_mostream;
}// end anon namespace
namespace MYSPACE
{
// create object - mostream
std::ostream & MYOSTREAM = s_mostream;
} // end namespace
.....
///// not tested in a compiler - I probably broke somthing but you
///// should get the drift