一部の 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 インスタンスを保持できないため、追跡できなくなります。
これを解決する方法はありますか?組み込み型の & または * を返すだけでなく、参照またはポインター クラスのインスタンスを返すことで解決できると思います。しかし、私はそれを行う方法がわかりません。
さらに、デバッガーでこのプログラムを実行できません。この問題は REAL 環境でのみ発生し、再現が非常に困難です。