Is there a nice way of including certain members only in the debug build of a program?
I have an indexed data structure of which I use a large number of instances, which carry certain status flag in case some contents of the data structure have changed, but the index hasn't been updated.
The status flag are only used to check that all uses of the index call the update
functionality in case the data has been changed, but for performance and storage reasons, since there are lots of instances and the data structure might be changed a lot before update
is called, I would like to keep this data only for the debug build.
There are basically two types of operations on these flags:
assert
ing that the flag is not set, i.e. certain parts of the index are still valid.Are there any nicer ways of achieving this than sprinkling my code with #ifndef NDEBUG
statements?
Note: In my special use case, the performance hit might not be that large, but I'm still looking for a general way to approach this, since there are probably much more complex use cases for the same idea.
You can reduce amount of #ifdefing by providing a base class with debug facilities:
class
t_MyDebugHelper
{
#ifdef NDEBUG
public: void
Set_Something(int value)
{
(void) value; // not used
}
public: void
Verify_Something(void)
{}
#else
private: ::std::string m_some_info;
private: int m_some_value;
public: void
Set_Something(int value)
{
m_some_value = value;
}
public: void
Verify_Something(void)
{
// implementation
}
#endif
};
class
t_MyClass
: public t_MyDebugHelper
{
public: void
SomeMethod(void)
{
t_MyDebugHelper::Verify_Something();
t_MyDebugHelper::Set_Something(42);
...
}
};
This method does not allow you to get rid of ifdef completely, however it allows to avoid them in the main code logic. In Release build all the debug helper functions will result in noop and t_MyDebugHelper
class won't increase target class size due to empty base class optimization. If debug helper needs an access to t_MyClass
methods then a CRTP could be applied.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With