
Martin Bonner wrote:
Has anybody got a "non-ignorable return" class that they could add to boost? (A class that encapsulates a return value whose destructor asserts/aborts if the return code has not been examined or deliberatedly ignored by the calling code.)
It would be a natural for this sort of application, and would be a generally useful utility class.
Attached is a toy implementation for such a thing. #ifndef TOY_INC_TEST_CHECKED_CODE_H #define TOY_INC_TEST_CHECKED_CODE_H #include <cassert> #ifndef TOY_TEST_CHECKED_CODE_DEFAULT_FAIL_POLICY #define TOY_TEST_CHECKED_CODE_DEFAULT_FAIL_POLICY assert_fail #endif #ifndef TOY_TEST_CHECKED_CODE_DEFAULT_CHECK_POLICY #ifndef NDEBUG #define TOY_TEST_CHECKED_CODE_DEFAULT_CHECK_POLICY flag_check #else #define TOY_TEST_CHECKED_CODE_DEFAULT_CHECK_POLICY no_check #endif #endif namespace toy { class assert_fail { public: static void fail() { assert(!"code wasn't tested"); } }; class flag_check { protected: flag_check() : m_check(false) {} bool was_checked() const { return m_check; } void check() const { m_check = true; } private: mutable bool m_check; }; class no_check { protected: static bool was_checked() { return true; } static void check() {} }; // // FailPolicy shouldn't throw (it's used in the dtor) // template< typename T, typename FailPolicy = TOY_TEST_CHECKED_CODE_DEFAULT_FAIL_POLICY, typename CheckPolicy = TOY_TEST_CHECKED_CODE_DEFAULT_CHECK_POLICY > class test_checked_code : public FailPolicy , public CheckPolicy { public: test_checked_code(T code) // implicit ctor : m_code(code) { } test_checked_code(const test_checked_code & other) : m_code(other) // conversion { } template<typename U, typename V, typename W> test_checked_code(const test_checked_code<U, V, W> & other) : m_code(static_cast<U>(other)) // conversion { } ~test_checked_code() { if (this->was_checked() == false) this->fail(); } operator T() const { this->check(); return m_code; } private: test_checked_code & operator= (const test_checked_code &); private: T m_code; }; } #endif