【发布时间】:2010-06-20 15:04:57
【问题描述】:
我有一个复杂的程序,有一个奇怪的错误,一些 int 值意外地降至零。
所以我想跟踪这个内置类型值,然后我可以轻松调试。
为此,我创建了 ValueWatcher 模板类,因此我可以跟踪值的几乎变化,除非 ValueWatcher 取消引用。 (我制作了这些取消引用运算符,因为程序需要 int *, &)
template <typename T>
class ValueWatcher
{
public:
ValueWatcher(const T &val)
{
cout << "constructor with raw value " << val << endl;
_cur = _old = val;
}
ValueWatcher(const ValueWatcher& vw)
{
cout << "constructor with ValueWatcher " << vw._cur << endl;
_cur = vw._cur;
}
ValueWatcher& operator=(const ValueWatcher &rhs)
{
cout << "operator= with ValueWatcher " << rhs._cur << endl;
_cur = rhs._cur;
onChanged();
return *this;
}
ValueWatcher& operator=(const T &val)
{
cout << "operator= with " << val << endl;
_cur = val;
onChanged();
return *this;
}
int *operator&()
{
cout << "addressing operator" << endl;
// can't track anymore!!!!!!!!!!!!!!!!!!!!!!!!!
return &_cur;
}
operator int&()
{
cout << "operator int&" << endl;
// can't track anymore!!!!!!!!!!!!!!!!!!!!!!!!!
return _cur;
}
operator int&() const
{
cout << "const operator int&" << endl;
return _cur;
}
operator int() const
{
cout << "operator int" << endl;
return _cur;
}
private:
void onChanged()
{
// update old and do proper action
}
T _cur;
T _old;
};
问题是,当客户端代码需要 ValueWatcher 的 int & 或 int * 时,它可以给出 int & 或 int * 但 - int * 或 & 不能保存 ValueWatcher 实例,因此无法再跟踪。
有没有办法解决这个问题?我认为它可以通过返回引用或指针类实例来解决,而不仅仅是返回 & 或 * 的内置 int 类型。但我不知道该怎么做。
此外—— 我不能用调试器运行这个程序。该问题仅在真实环境中出现,并且很难重现。
【问题讨论】:
-
也许带有条件断点的调试器会是一个更好的解决方案?
标签: c++ reference overloading dereference operator-keyword