Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Track member variable value change

Tags:

c++

class

c++11

I want to track when a particular member variable changes value so I can print it out. Now, the obvious solution to do this is to add a tracking function in the member's Set method, like so :

class Foo
{
public:
    Foo() {}

    void SetBar(int value)
    {
        //Log that m_bar is going to be changed
        m_bar = value;
    }
private:
    int m_bar; // the variable we want to track
};

The problem I'm facing is that I'm working on a huge project and some classes have a lot of methods that internally change member variables instead of calling their Setters.

m_bar = somevalue;

Instead of :

SetBar(somevalue);

So I'm wondering if there's a faster/more clean method to achieve what I want than just changing every m_bar = to SetBar(. An assignment operator overload only for that member variable perhaps?

like image 963
Hatted Rooster Avatar asked Nov 22 '15 12:11

Hatted Rooster


People also ask

Can a variable value be changed?

A variable is a data item whose value can change during the program's execution.

How can I change variable value while debugging in Visual Studio?

Solution 3Set a break point where your variable is used and start debugging. When execution stops at the break point, change the content of your variable in the local window and resume execution by pressing F5.

Is it possible to change the value of a variable while debugging?

In the debug session, use the step command or a breakpoint to reach the step for which you want to change variable values in the flow service. 3. In Variables view, right-click the variable whose value you want to change and select Change Value.


1 Answers

If it is possible for you to change the data type of the member, you can change it to a logger type.

Example:

#include <iostream>

template <class T>
class Logger
{
  T value;

public:

  T& operator=(const T& other)
  {
    std::cout << "Setting new value\n";
    value = other;
    return value;
  }

  operator T() const
  {
    return value;
  }

};

class Foo
{
public:
    Foo() {}

    void SetBar(int value)
    {
        //Log that m_bar is going to be changed
        m_bar = value;
    }

private:

#if 1
    Logger<int> m_bar; // the variable we want to track
#else
    int m_bar; // the variable we want to track
#endif

};

int main()
{
  auto f = Foo();
  f.SetBar(12);
}

Online example at ideone.

like image 161
Micha Wiedenmann Avatar answered Sep 27 '22 22:09

Micha Wiedenmann