SmartPointer模板

时间:2018-09-26 15:19:16

标签: c++ smart-pointers

我正在尝试实现SmartPointer模板类。当我说对的时候,基本上是shared_ptr。

#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;
}

我的问题是,获取getCounter函数的读取访问错误,并且*运算符仅返回地址。 我该如何运作? 我试图使用&运算符,但是我弄错了。

很高兴为您提供帮助!

1 个答案:

答案 0 :(得分:1)

这很突出:

SmartPointer(T *obj) {
    cout << "Konstruktor SmartPointer \n";
    _object = obj;
    *_counter++;      // I don't see _counter being initialized.
                      // So here you are incrementing the content of some
                      // random memory location.
}

这看起来是错误的:

SmartPointer& operator=(SmartPointer& sp) {
    ....
    if (*_counter > 0) {
        removeOne();
        sp._object = _object;
        sp._counter += 1;

        // Hold on you have not updated this object.
        //
        // You have made the other smart pointer point at your object
        // (which oucld have been deleted) but keep the reference
        // count for the old object and incremented it!!!!
        return *this;
    }
}

我写了一些关于智能指针的东西。我认为您肯定需要阅读。

Smart-Pointer - Unique Pointer
Smart-Pointer - Shared Pointer
Smart-Pointer - Constructors