Appendix B. Source Code for the files scpp_assert.hpp and scpp_assert.cpp

File scpp_assert.hpp

#ifndef __SCPP_ASSERT_HPP_INCLUDED__
#define __SCPP_ASSERT_HPP_INCLUDED__

#include <sstream> // ostringstream

#ifdef SCPP_THROW_EXCEPTION_ON_BUG
#include <exception>

namespace scpp {
// This exception is thrown when the sanity checks defined below fail,
// and #ifdef SCPP_THROW_EXCEPTION_ON_BUG.
class ScppAssertFailedException : public std::exception {
 public:
  ScppAssertFailedException(const char* file_name,
                unsigned line_number,
                const char* message);

  virtual const char* what() const throw () { return what_.c_str(); }

  virtual ~ScppAssertFailedException() throw () {}
 private:
  std::string what_;
};
} // namespace scpp
#endif

void SCPP_AssertErrorHandler(const char* file_name,
               unsigned line_number,
               const char* message);

// Permanent sanity check macro.
#define SCPP_ASSERT(condition, msg)                 \
    if(!(condition)) {                              \
        std::ostringstream s;                       \
        s << msg;                                   \
        SCPP_AssertErrorHandler(                    \
            __FILE__, __LINE__, s.str().c_str() );  \
  }

#ifdef _DEBUG
#  define SCPP_TEST_ASSERT_ON
#endif

// Temporary (for testing only) sanity check macro
#ifdef SCPP_TEST_ASSERT_ON
#  define SCPP_TEST_ASSERT(condition,msg) SCPP_ASSERT(condition, msg)
#else
#  define SCPP_TEST_ASSERT(condition,msg) // do nothing
#endif

#endif // __SCPP_ASSERT_HPP_INCLUDED__

File scpp_assert.cpp

#include "scpp_assert.hpp" #include <iostream> // cerr, endl, flush #include <stdlib.h> // exit() using namespace std; #ifdef SCPP_THROW_EXCEPTION_ON_BUG namespace ...

Get Safe C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.