For practice, I've implemented my own smart pointer class. It's a 'unique pointer', meaning it doesn't allow copies of itself (when copying from a
into b
, a
is 'emptied' after the copying, i.e. the raw pointer is set to 0
), so there can never be more than one time where delete
is called on the raw pointer.
It utilizes RAII to bound the memory deallocation to the object lifetime, so it is just a basic smart pointer.
#ifndef SMARTPOINTER_CPP
#define SMARTPOINTER_CPP
#include <iostream>
template <typename T>
class SmartPointer {
public:
SmartPointer(T* pointer = NULL) : pointer(pointer) { }
~SmartPointer(){
delete pointer;
}
SmartPointer(SmartPointer& other){
*this = other;
}
SmartPointer& operator=(SmartPointer& other){
this->pointer = other.pointer;
other.pointer = NULL;
return *this;
}
T& operator*() const {
return *pointer;
}
T* operator->() const {
return pointer;
}
private:
T* pointer;
template <typename E>
friend std::ostream& operator<<
(std::ostream& stream, const SmartPointer<E>& smartPointer);
};
template <typename E>
std::ostream& operator<<(std::ostream& stream, const SmartPointer<E>& smartPointer){
stream << smartPointer.pointer;
}
#endif
It's a 'unique pointer'
No its anauto ptr
. You should implement move semantics to get functionality likeunique ptr
\$\endgroup\$