Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- // #include <progrock/cpp/pointers/NullCheckingPtr.h>
- //
- // Formerly known as "ZPtr".
- // Copyright (c) 200x - 2012 Alf P. Steinbach
- //----------------------------------------------- Dependencies:
- #include <progrock/cpp/classkinds/SelfDestroyingObject.h> // cpp::DestructionEvent, cpp::SelfDestroyingObject
- #include <progrock/cpp/throwx.h> // cpp::hopefully, cpp::throwX
- #include <progrock/cpp/c++11_emulation.h> // CPP_NOEXCEPT
- #include <algorithm> // std::swap
- #include <stddef.h> // std::nullptr_t
- //----------------------------------------------- Interface:
- namespace progrock{ namespace cpp{
- using std::swap;
- using std::nullptr_t;
- template< class Pointee >
- class NullCheckingPtr
- : private DestructionEvent::Listener
- {
- private:
- Pointee* p_;
- virtual void on( DestructionEvent const& ) CPP_NOEXCEPT CPP_IS_OVERRIDE
- {
- p_ = nullptr;
- }
- Pointee* goodPointer() const
- {
- hopefully( p_ != 0 )
- || throwX( "cpp::NullCheckingPtr: attempted access of non-existent pointee" );
- return p_;
- }
- public:
- bool operator!() const CPP_NOEXCEPT { return (p_ != 0); }
- Pointee* operator->() const { return goodPointer(); }
- Pointee& operator*() const { return *goodPointer(); }
- void swapWith( NullCheckingPtr& other )
- {
- swap( p_, other.p_ );
- }
- void operator=( NullCheckingPtr other ) CPP_NOEXCEPT
- {
- swapWith( other );
- }
- ~NullCheckingPtr()
- {
- if( p_ != 0 )
- {
- p_->removeDestructionListener( *this );
- }
- }
- explicit NullCheckingPtr( Pointee* p = nullptr )
- : p_( p )
- {
- if( p_ != 0 )
- {
- p_->addDestructionListener( *this );
- }
- }
- NullCheckingPtr( NullCheckingPtr const& other )
- : p_( other.p_ )
- {
- if( p_ != 0 )
- {
- p_->addDestructionListener( *this );
- }
- }
- };
- template< class Pointee >
- inline bool operator==( NullCheckingPtr< Pointee > const& p, std::nullptr_t )
- CPP_NOEXCEPT
- {
- return !p;
- }
- template< class Pointee >
- inline bool operator==( std::nullptr_t, NullCheckingPtr< Pointee > const& p )
- CPP_NOEXCEPT
- {
- return !p;
- }
- template< class Pointee >
- inline bool operator!=( NullCheckingPtr< Pointee > const& p, std::nullptr_t )
- CPP_NOEXCEPT
- {
- return !!p;
- }
- template< class Pointee >
- inline bool operator!=( std::nullptr_t, NullCheckingPtr< Pointee > const& p )
- CPP_NOEXCEPT
- {
- return !!p;
- }
- template< class Pointee >
- inline void swap( NullCheckingPtr< Pointee >& a, NullCheckingPtr< Pointee >& b )
- CPP_NOEXCEPT
- {
- a.swapWith( b );
- }
- } } // namespace progrock::cpp
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement