轨道成员变量值更改

Track member variable value change

本文关键字:变量值 成员 轨道      更新时间:2023-10-16

我想跟踪特定成员变量何时更改值,以便打印出来。现在,显而易见的解决方案是在成员的Set方法中添加一个跟踪函数,如下所示:

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
};

我面临的问题是,我正在处理一个巨大的项目,有些类有很多方法可以在内部更改成员变量,而不是调用它们的Set ter。

m_bar = somevalue;

代替:

SetBar(somevalue);

所以我想知道是否有一种更快/更干净的方法可以实现我想要的,而不仅仅是将每个m_bar =更改为SetBar(。赋值运算符可能只为该成员变量重载?

如果可以更改成员的数据类型,则可以将其更改为记录器类型。

示例:

#include <iostream>
template <class T>
class Logger
{
  T value;
public:
  T& operator=(const T& other)
  {
    std::cout << "Setting new valuen";
    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);
}

ideone的在线示例。