How do I know if a global variable has changed in C ++?
I have a stupid question! Suppose you have a global variable that is used throughout your project and you are going to do something when it changes, such as calling a function.
One easy way is to call your function after every change. But what if this global variable is part of the library and will be used outside of it. Is there a better solution?
source to share
Presumably you want to find when your variable has changed without tracking down the reference to it and rewriting all that code that depends on it.
To do this, change your variable from what is now the type of the class that overloads operator=
and prints / writes / no matter what changes when it happens. For example, suppose you have:
int global;
and want to know when the changes are made global
:
class logger {
int value;
public:
logger &operator=(int v) { log(v); value= v; return *this; }
// may need the following, if your code uses `+=`, `-=`. May also need to
// add `*=`, `/=`, etc., if they're used.
logger &operator+=(int v) { log(value+v); value += v; return *this; }
logger &operator-=(int v) { log(value-v); value -= v; return *this; }
// ...
// You'll definitely also need:
operator int() { return value; }
};
and replace int global;
with logger global;
to get a log of all changes to global
.
source to share
Just to answer the real question: No, there is no way to define "when a variable changes" in C ++. Technically, if you have enough privileges and the hardware supports it, you can set a "write breakpoint" for your variable's address. But this is just a very cool way to achieve something that is EASILY achieved by renaming the variable and then fixing all the places the variable accesses to call the function to update the value, and if necessary also call the function at the same time - as it was suggested in multiple answers.
source to share