gpt4 book ai didi

c++ - 智能指针模板

转载 作者:行者123 更新时间:2023-11-28 04:32:25 25 4
gpt4 key购买 nike

我正在尝试实现一个 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 函数出现读取访问错误,而 * 运算符只返回地址。我怎样才能让它工作?我尝试使用 & 运算符,但我错了。

很高兴能得到您的帮助!

最佳答案

这很突出:

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

关于c++ - 智能指针模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52521166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com