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 NoCheckPolicy { NoCheckPolicy() { } static void Check(T *_p) { } }; template<typename T> struct FullCheckPolicy { FullCheckPolicy() { } FullCheckPolicy(const NoCheckPolicy<T>&) { } static void Check(T *_p) { if (!_p) { throw std::runtime_error("Null pointer!"); } } }; template<typename T, template<class> class CheckingPolicy = NoCheckPolicy> class SmartPtr : public CheckingPolicy<T> { private: T *p_; public: const T * getPtr() const { return p_; } T * getPtr() { return p_; } public: SmartPtr(T *p = NULL) : p_(p) { } template< template <class> class ChkPolicy> SmartPtr(const SmartPtr<T, ChkPolicy> &_ptr) : CheckingPolicy<T>(_ptr) { p_ = const_cast<T*>(_ptr.getPtr()); } template< template <class> class ChkPolicy> SmartPtr & operator = (const SmartPtr<T, ChkPolicy> &_other) { SmartPtr temp(_other); p_ = const_cast<T*>(_other.getPtr()); return *this; } const T * operator ->() const { CheckingPolicy<T>::Check(p_); return this->getPtr(); } T * operator ->() { CheckingPolicy<T>::Check(p_); return this->getPtr(); } const T & operator *() const { CheckingPolicy<T>::Check(p_); return this->getPtr(); } T & operator *() { CheckingPolicy<T>::Check(p_); 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 = nocheckPtr; //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
Straight Max-Min
C++ Car Racing game framework
candies
snake logic complete c++
generating all valid parenthesis
Cross Multiplication
Replace substring poor
LRU - template
Scope guarding
factor