diff --git a/code/smart_pointers.cpp b/code/smart_pointers.cpp new file mode 100644 index 0000000..ba66056 --- /dev/null +++ b/code/smart_pointers.cpp @@ -0,0 +1,28 @@ +#include +using namespace std; + +// A generic smart pointer class +template +class SmartPtr { + T* ptr; // Actual pointer +public: + // Constructor + explicit SmartPtr(T* p = NULL) { ptr = p; } + // Destructor + ~SmartPtr() { delete (ptr); } + // Overloading dereferncing operator + T& operator*() { return *ptr; } + // Overloading arrow operator so that + // members of T can be accessed + // like a pointer (useful if T represents + // a class or struct or union type) + T* operator->() { return ptr; } +}; + +int main() +{ + SmartPtr ptr(new int()); + *ptr = 20; + cout << *ptr; + return 0; +}