Re: C++ Tracking primitive type value change
ljh131 <ljh...@gmail.com> wrote:
i have a complex program with weird bug that some int value is down to
zero unexpectedly.
so i want tracking this built-in type value, then i could debug
easily.
to do that, i made following ValueWatcher template class so i could
track almost changes of value except when ValueWatcher is
dereferencing. (i made these dereferencing operators because the
program needs 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 ValueWatc=
her &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 opera=
tor" << 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 i=
nt&" << endl;
return _cur;
}
operator int() const
{
cout << "operator int" <<=
endl;
return _cur;
}
private:
void onChanged()
{
// update old and do prop=
er action
}
T _cur;
T _old;
};
the problem is, when client code wants int & or int * of ValueWatcher,
- it can gives int & or int * anyway but - int * or & cannot hold
ValueWatcher instance, so can't tracking anymore.
is there anyway to solve this? i think it can be solved by returning
reference or pointer class instance instead of just returning & or *
of built-int type. but i don't know how to do that.
As a side note, you shouldn't use names starting with an underscore -
that range of names is reserved for the implementation. As =D6=F6 Tiib
suggested, stepping through the program with a debugger is advisable.
Breakpoints, conditional breakpoints and watchers will help you.
If you can touch the client code, you could do some debugging by hand
- that is, nail down the moment that the bug appears by printing out
the misbehaving variable at the entrance and at the exit of the
functions - also consider using some asserts in the critical points -
i.e. before calling a function that expects that variable not to be 0.
Hope that helps.
--
FSC
http://userscripts.org/scripts/show/59948