Lets imagine such a code example:
class MyStaticSingleton {
public:
static const MyStaticSignleton INSTANCE;
~MyStaticSignleton() = default;
bool flag = predicate();
private:
MyStaticSignleton() = default;
MyStaticSignleton(const MyStaticSignleton&) = default;
static bool predicate() throw() {
const auto v1 = -1, v2 = 2;
return static_cast<bool>(v1 + v2);
}
};
As you can see:
1) there is
only one instance of the
MyStaticSingleton
class is possible,
AND it is both
static
AND constant simultaneously.
2)
flag
value, as a subobject of the
static const
cobject is, in fact,
static const
too.
3)
flag
value is setted
once per process execution, during initialization phase (as a subobject of the
static
object)
AND then
never changed.
4) the
predicate
function seems to be very predictable in it's return value, as it operates of
compile time consts
AND so returns the
compile time const
, making it very attractive for the optimizing compiler to be rewrited to the one single line:
return true;
AND then just
inline, effectively removing the function call.
As the optimizing complier tends to get rid of
ANY code, which he assumes he can throw out without changing the observable behaviour of a program, i'm condiser that there would be nothing done in the runtime, but just one single
true
flag exist, which will be
compile time const
AND would be even
allocated during compile time
(in the executable file).
Thats seems to be
no problem here, at first sight,
BUT that isn't true. In fact, that
-1 AND 2 (this is just abstract examples, do
NOT tie yourself to that exact values), while predictable
compile time constants
on the current hardawre platform, can be completely diffirent value on the other (platform), making so the result compiled code stricly platform-dependant.
What I have tried:
So we need to run the exact code in the
run time always, the obvious solution is to mark te instance
volatile
denying here most-to-any optimizations:
class MyStaticSingleton {
public:
static const volatile MyStaticSignleton INSTANCE;
...
I assume that would remove the problem
OR may be i'm wrong?
May be there are also
other solutions to ensure some code code would be executed at run time,
NOT compile time?
As we have
C++11 constexpr
to ensure the code will be runned compile time,
NOT run time, is there an exact reverse?