61 lines
1.2 KiB
C++

#ifndef NALOGA0901_SMARTPOINTER_H
#define NALOGA0901_SMARTPOINTER_H
#include "ReferenceCounter.h"
template<typename T>
class SmartPointer {
private:
T *pointer;
ReferenceCounter *used;
public:
SmartPointer() {
used = new ReferenceCounter();
++*used;
}
SmartPointer(T *pointer) : pointer(pointer) {
used = new ReferenceCounter();
++*used;
}
SmartPointer(const SmartPointer<T> &p1) : pointer(p1.pointer), used(p1.used) {
++*used;
}
~SmartPointer() {
if (--*used == 0) {
delete pointer;
delete used;
}
}
T &operator*() {
return *pointer;
}
T *operator->() {
return pointer;
}
SmartPointer<T> &operator=(const SmartPointer<T> &sp) {
if (this != &sp) {
if (--*used == 0) {
delete pointer;
delete used;
}
pointer = sp.pointer;
used = sp.used;
++*used;
}
return *this;
}
unsigned int useCount() {
return used->useCount();
}
};
#endif //NALOGA0901_SMARTPOINTER_H