Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef SMARTPOINTER_H
- #define SMARTPOINTER_H
- template <class T>
- class SmartPointer
- {
- T* m_pointer;
- int* m_referenceCounter;
- public:
- SmartPointer();
- ~SmartPointer();
- // the referenceCounter is increased by the copyconstructor
- SmartPointer(const SmartPointer<T>& smartPointer);
- // the referenceCounter is increased also increased by the = operator
- SmartPointer<T>& operator=(const SmartPointer<T>& smartPointer);
- T& operator*() const;
- T* operator->() const;
- // we need to overload -> and *
- };
- // for templates we do everything in one file
- template <class T>
- SmartPointer<T>::SmartPointer()
- {
- this->m_referenceCounter = new int();
- *(this->m_referenceCounter) = 1; // why 1?
- this->m_pointer = new T();
- }
- template <class T>
- SmartPointer<T>::~SmartPointer()
- {
- if (m_referenceCounter == 0)
- {
- delete this->m_referenceCounter;
- delete this->m_pointer;
- this->m_referenceCounter == NULL;
- this->m_pointer == NULL;
- }
- }
- template <class T>
- SmartPointer<T>::SmartPointer(const SmartPointer<T>& smartPointer)
- {
- // increment the referenceCounter
- smartPointer.m_referenceCounter++;
- this->m_referenceCounter = smartPointer.m_referenceCounter;
- this->m_pointer = smartPointer.m_pointer;
- }
- template <class T>
- SmartPointer<T>& SmartPointer<T>::operator=(const SmartPointer<T>& smartPointer)
- {
- // increment the referenceCounter
- smartPointer.m_referenceCounter++;
- this->m_referenceCounter = smartPointer.m_referenceCounter;
- this->m_pointer = smartPointer.m_pointer;
- }
- template <class T>
- T& SmartPointer<T>::operator*() const
- {
- return (*m_pointer);
- }
- template <class T>
- T* SmartPointer<T>::operator->() const
- {
- return (m_pointer);
- }
- #endif // SMARTPOINTER_H
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement