If you have a choice, please pass it as a parameter, if you really really don't have any choice, then you could consider about singleton.
c++11
template<typename T>
class meyersSingleton
{
public:
static T& instance()
{
static T theSingleton;
return theSingleton;
}
meyersSingleton() = delete;
~meyersSingleton() = delete;
meyersSingleton(meyersSingleton const&) = delete;
meyersSingleton& operator=(meyersSingleton const&) = delete;
};
c++98
template<typename T>
class meyersSingleton
{
public:
static T& instance()
{
static T theSingleton;
return theSingleton;
}
private :
meyersSingleton();
~meyersSingleton();
meyersSingleton(meyersSingleton const&);
meyersSingleton& operator=(meyersSingleton const&);
};
you could use it as this way
#include <cstdio>
template<typename T>
class meyersSingleton
{
public:
static T& instance()
{
static T theSingleton;
return theSingleton;
}
meyersSingleton() = delete;
~meyersSingleton() = delete;
meyersSingleton(meyersSingleton const&) = delete;
meyersSingleton& operator=(meyersSingleton const&) = delete;
};
void read_file()
{
char buffer [100];
fgets (buffer , 100 , meyersSingleton<FILE*>::instance());
printf("%s", buffer);
}
int main()
{
FILE **a = &meyersSingleton<FILE*>::instance();
*a = fopen("coeff", "rb");
read_file();
return 0;
}
not a very intuitive solution, but it will guarantee you only have a global and single FILE.
If you need more single FILE, you could add one more template parameter
template<typename T, size_t N = 0>
class meyersSingleton
{
public:
static T& instance()
{
static T theSingleton;
return theSingleton;
}
meyersSingleton() = delete;
~meyersSingleton() = delete;
meyersSingleton(meyersSingleton const&) = delete;
meyersSingleton& operator=(meyersSingleton const&) = delete;
};
If you are using c, then just omit this solution.
Edit : In most of the cases, singleton considered as a bad solution, an anti-pattern which
should no be used and leave it alone.Here are some good articles discussing about the pros and cons of singleton.
why singleton is so bad
Singleton I love you, but you're bringing me down
Don't take me wrong, singleton do solve one problem--it guarantee you will only have one
object(variable, resource, whatever) at a time, sometimes this is very useful(although it
is rare).Log is an example, we need log everywhere, and the log wouldn't write something into our program.