Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create externally unmodifiable variable?

Tags:

c++

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&?

like image 587
kocica Avatar asked Dec 03 '22 19:12

kocica


2 Answers

Instead of const double & you can change your API to provide a function double getTime(); which returns the value of simTime.

like image 163
Georgi Gerganov Avatar answered Dec 21 '22 23:12

Georgi Gerganov


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
like image 33
Stephan Lechner Avatar answered Dec 22 '22 00:12

Stephan Lechner