mNo edit summary Tags: Visual edit apiedit |
|||
Line 46: | Line 46: | ||
This template is an example of [[Catching defects with Patterns]]. |
This template is an example of [[Catching defects with Patterns]]. |
||
+ | |||
⚫ | |||
+ | == Reference == |
||
+ | Stack Overflow: [http://stackoverflow.com/a/43386572/75129 link][[Category:C Plus Plus]] |
||
[[Category:Cheat]] |
[[Category:Cheat]] |
||
⚫ |
Latest revision as of 08:07, 13 April 2017
Ignoring Function Return Values[]
If it is important that a return value not be ignored by the caller of a function, the template dont_ignore may be used as follows:
BEFORE:
int add( int x, int y ) { return x + y; }
AFTER:
dont_ignore<int> add( int x, int y ) { return x + y; }
When the caller of the function does not use the return value, an exception is thrown. Definition of dont_ignore:
template<class T> struct dont_ignore { const T v; bool used; dont_ignore( const T& v ) : v( v ), used( false ) {} ~dont_ignore() { if ( !used ) throw std::runtime_error( "return value not used" ); } operator T() { used = true; return v; } };
This template is an example of Catching defects with Patterns.
Reference[]
Stack Overflow: link