From 541c6019099794fa925803075883566bcda2c3e8 Mon Sep 17 00:00:00 2001 From: syntheticpp Date: Wed, 10 Dec 2008 20:22:40 +0000 Subject: [PATCH] add error policy to check return git-svn-id: svn://svn.code.sf.net/p/loki-lib/code/trunk@908 7ec92016-0320-0410-acc4-a06ded1c099a --- include/loki/CheckReturn.h | 28 +++++++++++++++++++++++++--- test/CheckReturn/main.cpp | 15 +++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/include/loki/CheckReturn.h b/include/loki/CheckReturn.h index 74c2c08..8b3854e 100755 --- a/include/loki/CheckReturn.h +++ b/include/loki/CheckReturn.h @@ -17,6 +17,8 @@ #include +#include + namespace Loki { @@ -42,7 +44,26 @@ namespace Loki /// can work with other types that have cheap copy operations. //////////////////////////////////////////////////////////////////////////////// -template < class Value > + +struct TriggerAssert +{ + static void run() + { + assert( 0 ); + } +}; + + +struct FprintfStderr +{ + static void run() + { + fprintf(stderr, "CheckReturn: return value was not checked\n"); + } +}; + + +template < class Value , typename OnError = TriggerAssert> class CheckReturn { public: @@ -61,9 +82,10 @@ public: /// Destructor checks if return value was used. inline ~CheckReturn( void ) { - // If this assertion fails, then a function failed to check the + // If m_checked is false, then a function failed to check the // return value from a function call. - assert( m_checked ); + if (!m_checked) + OnError::run(); } /// Conversion operator changes CheckReturn back to Value type. diff --git a/test/CheckReturn/main.cpp b/test/CheckReturn/main.cpp index f10e095..c766dda 100755 --- a/test/CheckReturn/main.cpp +++ b/test/CheckReturn/main.cpp @@ -26,6 +26,8 @@ typedef ::Loki::CheckReturn< bool > BoolReturn; typedef ::Loki::CheckReturn< string > StringReturn; +typedef ::Loki::CheckReturn< bool , ::Loki::FprintfStderr > BoolReturnStderr; + // ---------------------------------------------------------------------------- @@ -41,6 +43,14 @@ BoolReturn CheckRequired( void ) return BoolReturn( true ); } +// ---------------------------------------------------------------------------- + +BoolReturnStderr CheckRequiredStderr( void ) +{ + return BoolReturnStderr( true ); +} + + // ---------------------------------------------------------------------------- BoolReturn CheckRequired( bool value ) @@ -143,6 +153,11 @@ int main( unsigned int argc, const char * argv[] ) cout << "Made a nested call to CheckRequired." << endl; } + { + BoolReturnStderr check = CheckRequiredStderr(); + } + cout << "There should be a error message: \nCheckReturn: return value was not checked" << endl; + // This should assert since caller does not check return value. CheckRequired(); cout << "Should assert before this line! How did we get here?" << endl;