C++ 变量变化监视器

sup*_*max 4 c++ debugging

出于调试目的,我想找到一种方法来自动跟踪我的设计中涉及的变量的变化。

我想获得的结果就像每次分配变量时新值的printf,但没有手动插入所有printf。

做这个的最好方式是什么?谢谢

Ada*_*eld 6

为要监视的变量创建一个新类并定义适当的operator=赋值运算符方法:

template <class T>
class MonitoredVariable
{
public:
    MonitoredVariable() {}
    MonitoredVariable(const T& value) : m_value(value) {}

    T operator T() const { return m_value; }

    const MonitoredVariable& operator = (const T& value)
    {
        printf("Variable modified\n");
        m_value = value;
        return *this;
    }
private:
    T m_value;
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

MoniredVariable<int> x;
x = 42;  // Will print "Variable modified"
Run Code Online (Sandbox Code Playgroud)

当然,这是有用的,你必须包括在相关信息operator=执行,并且你也有超载其它算术赋值运算符,如+=-=等。