InterviewSolution
Saved Bookmarks
| 1. |
What is a Smart Pointer? Where it is used? What are types of Smart Pointers? Implement a generic Smart Pointer which can be used for all datatypes. |
|
Answer» Smart Pointers are used for better garbage collection so that there are no memory leaks. Using Smart Pointers, there is no NEED to call delete for any memory allocated dynamically and it gets automatically deallocated. Smart Pointers Implementations can be found in C++11 and higher versions. C++11 libraries provide four kinds of Smart pointers namely: auto_ptr, unique_ptr, shared_ptr and weak_ptr. The below example implements a generic smart pointer which can used for all datatypes: #include<iostream> using namespace std; template <class T> class SmartPtr { T *ptr; public: // Constructor explicit SmartPtr(T *p = NULL) { ptr = p; } // Destructor ~SmartPtr() { delete(ptr); } // Overloading dereferncing operator T & operator * () { return *ptr; } // Overloding 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<int> ptr(new int()); *ptr = 20; cout << *ptr; return 0; } |
|