I'm developing simple simulation library and came across problem, where I have simulation Time
variable, which shouldn't be modifiable by API user (programmer) at any circumstances (just provide information about simulation time), but should be modifiable by simulation library, so it cannot be constant.
This is what I came up with yet but it seems a little bit tricky to me
double simTime; // Internal time, modified by library
const double& Time = simTime; // Time info provided for programmer in API
Is there an approach for this without const double&
?
Instead of const double &
you can change your API to provide a function double getTime();
which returns the value of simTime
.
I find the const double&
-solution rather straight forward and elegant, and I don't see any negative side effects.
The only thing is that your library should declare simTime
either as static
or in an anonymous namespace such that it cannot be addressed from outside. Otherwise, any extern double simTime
in any other translation unit would expose simTime
.
So write...
// library.cpp:
static double simTime;
const double &simTimePublic = simTime;
// library.h:
extern const double &simTimePublic;
// userCode.cpp:
#include "library.h"
...
double simTimeCopy = simTimePublic;
// simTimePublic = 1.0; // illegal
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With