I'm trying to implement a SmartPointer template Class. Basically shared_ptr, when i'm right.
#include <iostream>
using namespace std;
template <typename T>
class SmartPointer
{
T *_object;
int *_counter;
void removeOne() {
*_counter -= 1;
if (*_counter == 0) {
delete _object;
}
}
public:
SmartPointer(T *obj) {
cout << "Konstruktor SmartPointer \n";
_object = obj;
*_counter++;
}
SmartPointer(SmartPointer& sp) {
cout << "Kopier-Konstruktor SmartPointer \n";
_object = sp._object;
sp._counter += 1;
_counter = sp._counter;
}
~SmartPointer() {
cout << "Destruktor SmartPointer \n";
removeOne();
}
SmartPointer& operator=(SmartPointer& sp) {
cout << "Zuweisungsoperator SmartPointer \n";
if (this == &sp) {
return *this;
}
if (*_counter > 0) {
removeOne();
sp._object = _object;
sp._counter += 1;
return *this;
}
}
int getCounter() {
return *_counter;
}
T* operator*() {
return _object;
}
};
template <typename T>
int fkt(SmartPointer<T> x) {
cout << "fkt:value = " << *x << endl;
cout << "fkt:count = " << x.getCounter() << endl;
return x.getCounter();
}
int main() {
SmartPointer<double> sp(new double(7.5));
fkt(sp);
return 0;
}
My Problem is that get an read access error for the getCounter function and that the * operator just returns the address. How can i make it work? I tried to use the & operator, but got i wrong.
Glad for every help!