How can I make a DEBUG function in C++ such as ConditionalAttribute in C#
In C#, one can make a method such as this:
[Conditional("DEBUG")]
private void MyF开发者_如何学编程unction()
{
}
In release, this method will no longer "exist".
Using C++, I have a class where I want to perform the same assertions at the beginning of every method, so I would like to put the group of assertions in their own method. If I chose to do it that way, would I have to rely on the compiler optimizing out an empty function (since asserts will be optimized out as well)? For example:
class MyClass
{
private:
void DebugFunction()
{
assert(...);
assert(...);
assert(...);
// ...
}
};
Or would I have to introduce a macro:
#ifdef NDEBUG
#define DebugFunction
#endif
What's the best way to do this?
The compiler will definitely optimize out the empty functions. I would prefer the function of asserts
over different versions of the code for debug and release. Of course, you should name the function appropriately, and document your reasons as well :-)
If, for some reason, you absolutely did have the urge to use #ifndef
, make sure you do it inside the CheckState()
function. This allows you to perform checks in release mode as well, should you later decide to do so. For example:
class MyClass
{
private:
void CheckState()
{
assert(...);
assert(...);
#ifndef NDEBUG
// some expensive check to only run on Debug builds
#endif
// Some check you want to always make
}
}
精彩评论