智能指针是C++11引入用于解决内存泄漏的情况,因为经常使用裸指针常在河边走,必然要湿鞋。但是需要注意的是智能指针和线程安全完全是两个事情。
shared_ptr
代码演示
template <typename T>
class SharedPtr {
private:
T* ptr; // 实际对象的指针
int* ref_count; // 引用计数指针
public:
// 构造函数
explicit SharedPtr(T* p = nullptr) : ptr(p) {
if (ptr) {
ref_count = new int(1); // 初始化引用计数为1
} else {
ref_count = nullptr;
}
}
// 拷贝构造函数
SharedPtr(const SharedPtr<T>& other) {
ptr = other.ptr;
ref_count = other.ref_count;
if (ref_count) {
(*ref_count)++; // 增加引用计数
}
}
// 析构函数
~SharedPtr() {
if (ref_count) {
(*ref_count)--; // 减少引用计数
if (*ref_count == 0) {
delete ptr; // 如果引用计数为0,释放对象内存
delete ref_count; // 释放引用计数的内存
}
}
}
// 重载 `*` 操作符
T& operator*() const {
return *ptr; }
// 重载 `->` 操作符
T* operator->() const {
return ptr; }
// 重载赋值操作符
SharedPtr<T>& operator=(const SharedPtr<T>& other) {
if (this != &other) {
// 先减少当前引用计数
if (ref_count) {
(*ref_count

最低0.47元/天 解锁文章
&spm=1001.2101.3001.5002&articleId=146436445&d=1&t=3&u=c7d106b90cdf445a92ca54b3c4a53ab6)
100

被折叠的 条评论
为什么被折叠?



