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?

+3


source to share


5 answers


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

.

+8


source


I would say the easiest way is to create a set method on your variable that calls the function, and let it be public and the variable itself private:



//public
void setYourVariable(int newValue)
{
    YourVariable = newValue;
    YourFunction();
}
//private 
int YourVariable;

      

+4


source


You need to make an accessor function to set a global variable. Then you can call your custom function from that accessor instead of requiring all callers to do it themselves.

+2


source


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.

+1


source


Since u says it can also be called from the side, since Kevin said it is good to have Get () and Set (...) methods. Mainly 2 benefits. 1) Through the set, u can call a function or do an action whenever the value changes. 2) You can avoid directly affecting your variable outwardly.

0


source







All Articles