Directing ATL/CRT assertions to file or debug output
In real life the test organization is running overnight simulations, performance tests or stress tests on your codebase. In some cases it’s done with debug build which means that the assertions in your code will be enabled. Quite often somebody will start the test run at 08:00 PM, return next morning, and discover that after 30 minutes of execution this nice message-box saying that an assertion failed suddenly appeared ;-( As a net result your entire run is blocked and no actionable metrics is gathered. Sure, you need to investigate every assertion and understand what’s wrong, but sometimes you may not care. People assert all kind of different things and some invariants, pre- and post-conditions may not be relevant to what you’re trying to accomplish. To paraphrase Orwell: all assertions are equal but some assertions are more equal than others.
Second common scenario IRL is that really paranoid (or should we say diligent?) people tend to write code like this:
HRESULT SomeFunc(const CComBSTR& strFoo, int *pBar)
{
ATLASSERT(0 != strFoo.Length()); // Make some noise in debug builds.
ATLASSERT(0 != pBar);
if (0 == strFoo.Length()) // Handle the error properly in release builds.
{
return E_INVALIDARG;
}
else if (0 == pBar)
{
return E_POINTER;
}
...
}
Before adding this code into a live codebase, a decent developer would really like to step through every code path in debugger and make sure that without assertions being enabled all the error conditions will be properly handled. While doing something like this, I personally get very annoyed by these message-boxes ;-) Well, how to still make sure that assertions will be triggered when appropriate, but not to have any visual side-effects? Fortunately C run-time library provides you everything you need: _Crt* functions are the key, especially _CrtSetReportMode and _CrtSetReportFile, and also the documentation about CRT assertion macros. Enough talk, let’s see how to direct assertions to debug output :
#include <crtdbg.h>
#include <cstdlib>
int main()
{
// The line which does all the magic.
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
int i = 0;
_ASSERTE(0 != i);
return EXIT_SUCCESS;
}
This is actually one of these features I always needed, but lived years without knowing that it already existed ;-( Moral of the story: one should read more MSDN and/or CRT source code. What about ATL mentioned in the title? You’re lucky again, as MSDN says “The ATLASSERT macro performs the same functionality as the _ASSERTE macro found in the C run-time library.” Looking at file “atldef.h” in your nearest Visual Studio installation will confirm this.