Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Policy based smart pointer
//Title of this code #include <iostream> #include <stdexcept> template<typename T> struct FullCheckPolicy { static void Check(T *_p) { if (!_p) { throw std::runtime_error("Null pointer!"); } } }; template<typename T> struct NoCheckPolicy { static void Check(T *_p) { } }; template<typename T, template<typename E> class CheckingPolicy = NoCheckPolicy> class SmartPtr { private: T *p_; public: const T * getPtr() const { CheckingPolicy<T>::Check(p_); return p_; } T * getPtr() { CheckingPolicy<T>::Check(p_); return p_; } public: SmartPtr(T *p = NULL) : p_(p) { } template< template <typename F> class ChkPolicy> SmartPtr(const SmartPtr<T, ChkPolicy> &_ptr) { p_ = const_cast<T*>(_ptr.p_); } template< template <typename F> class ChkPolicy> SmartPtr & operator = (const SmartPtr<T, ChkPolicy> &_other) { p_ = const_cast<T*>(_other.p_); } const T * operator ->() const { return this->getPtr(); } T * operator ->() { return this->getPtr(); } const T & operator *() const { return this->getPtr(); } T & operator *() { return *this->getPtr(); } }; template<typename T> SmartPtr<T> make_smart(const T &val) { SmartPtr<T> ptr = new T(val); return ptr; } int main() { SmartPtr<int, FullCheckPolicy> ptr; SmartPtr<int, NoCheckPolicy> nocheckPtr = ptr; std::cout<<*nocheckPtr<<'\n'; std::cout<<*ptr<<'\n'; ptr = make_smart(3); nocheckPtr = ptr; std::cout<<*ptr<<'\n'; *ptr = 4; std::cout<<*ptr<<'\n'; }
run
|
edit
|
history
|
help
0
Handling new types without using RTTI
Silly circular pointer
czekolada
Day3
Overland pg. 68
member initial list
BinTree
11933
FindKthElementDivideConquer
Policy based smart pointer