How to find out if a global variable has changed in c++?

c++

Solution

Presumably you want to find when your variable is modified without tracking down ever reference to it and rewriting all that code that depends on it.

To do that, change your variable from whatever it is now to a class type that overloads `operator=`, and prints/logs/whatever the change when it happens. For example, let's assume you currently have:

int global;

and want to know when changes are made to `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 the `int global;` with `logger global;` to get a log of all the changes to `global`.

Problem

I have a silly question! Let's suppose you have a global variable that is used all over the project and you are going to do something when it changes ,for example calling a function . One simple way is to call your function after every change. But what if this global variable is part of a library and will be used outside .Is there any better solution ?

Original source