Advertisement
Guest User

Null-safe pointer

a guest
Sep 12th, 2015
459
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. #ifdef __OPTIMIZE__
  2. void __null_pointer_error() __attribute__((error ("Unsafe access to pointer")));
  3. #else
  4. #warning "You should turn on optimization!"
  5. #include <stdexcept>
  6.  
  7. class NullPointerException : public std::exception {
  8.         public:
  9.                 inline const char *what() throw() { return "NullPointerException"; }
  10.                 inline ~NullPointerException() throw() {}
  11. };
  12.  
  13. void __null_pointer_error() __attribute__((warning ("Pointer access without optimization!")));
  14. inline void __null_pointer_error() { throw NullPointerException(); }
  15. #endif
  16.  
  17. template <typename T>
  18. class Ptr {
  19.         public:
  20.                 inline Ptr(T *ptr = NULL) : mPtr(ptr) {}
  21.  
  22.                 inline operator bool() const __attribute__((const)) {
  23.                         return !!mPtr;
  24.                 }
  25.  
  26.                 inline T *operator->() const __attribute__((const)) {
  27.                         if(!*this) throw __null_pointer_error();
  28.                         return mPtr;
  29.                 }
  30.  
  31.                 inline T &operator*() const __attribute__((const)) {
  32.                         if(!*this) __null_pointer_error();
  33.                         return *mPtr;
  34.                 }
  35.  
  36.                 inline Ptr<T> &operator=(const Ptr &other) __attribute__((const)) {
  37.                         mPtr = other.mPtr;
  38.                         return *this;
  39.                 }
  40.  
  41.                 inline Ptr<T> &operator=(T *other) __attribute__((const)) {
  42.                         mPtr = other;
  43.                         return *this;
  44.                 }
  45.         private:
  46.                 T *mPtr;
  47. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement