First off, note that you get a different version of _member
in each translation unit! I'm not sure if that is intentional or not.
If you actually want one _member
in your program and you don't want the user to access a specific global variable, you shouldn't make it visible in the header! Put it into the source and provide functions to access it there:
// some-module.h
double getValue();
void setValue(double value);
// some-module.cpp
#include "some-module.h"
static double value(0.01);
double getValue() { return value; }
void setValue(double value) { ::value = value; }
I left out namespaces because they actually don't matter. You can use an unnamed namespace instead of static
inside the translation unit but it doesn't make much of a difference, really.
If you claim that the extra function call is unacceptable and everything has to be in the header, you could make value a private member of a class. You'd still need to wrap it into a function to avoid duplicated symbols. If you also wrap the class into an unnamed namespace, you can have one version of the value per translation unit, too:
#if ONE_VALUE_PER_TRANSLATION_UNIT
namespace {
#endif
class Value
{
static double& value() { static double rc(0.01); return rc; }
friend double getValue();
friend void setValue(double value);
};
double getValue() { return Value::value(); }
void setValue(double value) { Value::value() = value; }
#if ONE_VALUE_PER_TRANSLATION_UNIT
}
#endif
Obviously, you can add more function accessing the value in all of these case. I just demonstrated access using simple non-member function getValue()
and setValue()
. What you really expose is up to you.