Reputation: 7891
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 ?
Upvotes: 3
Views: 1461
Reputation: 490348
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
.
Upvotes: 8
Reputation: 395
Since u are saying it may get called from out side also, as Kevin said it is good to have Get() and Set(...) methods . Mainly 2 advantages. 1) Through the set u can call a function or do action whenever value changes. 2) You can avoid directly exposing your variable to the outside directly.
Upvotes: 0
Reputation: 26078
I'd say the easiest way is to create a set method for your variable that calls the function and let it be public, while the variable itself remains private:
//public
void setYourVariable(int newValue)
{
YourVariable = newValue;
YourFunction();
}
//private
int YourVariable;
Upvotes: 4
Reputation: 129454
Just to answer the actual question: No, there isn't a way to determine "when a variable changes" in C++. Technically, if you have enough privilege and the hardware supports it, you could set a "breakpoint on write" for the address of your variable. But it's just a very roundabout way to achieve something that is EASILY achieved by renaming the variable, and then fix all the places where the variable is being accessed to call a function to update the value, and if appropriate also call a function at the same time - as suggested in several answers.
Upvotes: 1
Reputation: 225032
You need to make an accessor function to set your global variable. Then you can call your special function from that accessor instead of requiring all of the callers to do it themselves.
Upvotes: 2