/* * smart-pointer-copy-policy.cc */ #include using namespace std; template struct deep_copy { static void copy(T*& destination, T*& source) { destination = new T(*source); } }; template struct destructive_copy { static void copy(T*& destination, T*& source) { destination = source; source = 0; } }; template class copier = deep_copy> class smart_ptr : private copier { public: smart_ptr(T* p) : ptr_(p) {} ~smart_ptr() { delete ptr_; } smart_ptr(smart_ptr& value) { smart_ptr::copy(ptr_, value.ptr_); } smart_ptr& operator=(smart_ptr& rhs) { T* tmp_ptr; smart_ptr::copy(tmp_ptr, rhs.ptr_); // Safe now ... delete ptr_; ptr_ = tmp_ptr; return *this; } T* operator->() { return ptr_; } T& operator*() { return *ptr_; } private: T* ptr_; }; int main() { smart_ptr sp1(new int(1)); // Deep copy by default // smart_ptr sp1(new int(1)); cout << *sp1 << endl; *sp1 = 2; cout << *sp1 << endl; smart_ptr sp2(sp1); // Deep copy by default // smart_ptr sp2(sp1); cout << *sp1 << endl; // Not if destructive copy (sp1 == 0) cout << *sp2 << endl; sp1 = sp2; // copy assignment return 0; }