为了调试目的,我想找到一种自动跟踪设计中涉及变量的更改的方法。
我希望得到的结果是,在每次分配变量时自动显示新值的 printf,但不需要手动插入所有的 printf。
最好的方法是什么? 谢谢。
我希望得到的结果是,在每次分配变量时自动显示新值的 printf,但不需要手动插入所有的 printf。
最好的方法是什么? 谢谢。
创建一个新的类来监控你想要的变量,并定义适当的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;
}
使用示例:
MoniredVariable<int> x;
x = 42; // Will print "Variable modified"
operator=
实现中包含相关信息,并且还必须重载其他算术赋值运算符,如+=
,-=
等。{{链接1:WaitOnAddress}}
ULONG g_TargetValue; // global, accessible to all threads
ULONG CapturedValue;
ULONG UndesiredValue;
UndesiredValue = 0;
CapturedValue = g_TargetValue;
while (CapturedValue == UndesiredValue) {
WaitOnAddress(&g_TargetValue, &UndesiredValue, sizeof(ULONG), INFINITE);
CapturedValue = g_TargetValue;
}
template<class T>
struct proxy
{
//add const version
T & operator * ()
{
std::cout << "access" << std::endl;
return val_;
}
T * operator -> ()
{
std::cout << "access" << std::endl;
return &val_;
}
proxy<T> & operator = (T const & other)
{
std::cout << "access" << std::endl;
val = other;
return (*this);
}
private:
T val_;
};
proxy<int> i;
那么 i = 12
和 *i = 12
将会产生相同的效果。 - Jon Purdy