c++智能指针的简单实现

本文探讨了C++中智能指针的基本概念,并详细解释了如何通过自定义 deleter 实现一个简单的智能指针类。内容涵盖智能指针的作用、所有权转移以及自定义 deleter 的必要性。通过实例代码展示,读者将更好地理解智能指针如何有效管理动态内存,防止内存泄漏。
摘要由CSDN通过智能技术生成
#include <iostream>
#include <cmath>
#include <algorithm>
#include <utility> //用于pair

using namespace std;

template<typename T>
class myShared_ptr {
   
public:
	explicit myShared_ptr(T* ptr = nullptr) : _ptr(ptr), _count(new int
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
智能指针是一种用于自动管理动态分配内存的工具。其中最常见的智能指针C++中的std::shared_ptr和std::unique_ptr。下面是一个简单实现智能指针的示例: ```c++ #include <iostream> template <typename T> class SmartPointer { public: SmartPointer(T* ptr) : ptr_(ptr), ref_count_(new size_t(1)) { } SmartPointer(const SmartPointer<T>& other) : ptr_(other.ptr_), ref_count_(other.ref_count_) { ++(*ref_count_); } ~SmartPointer() { if (--(*ref_count_) == 0) { delete ptr_; delete ref_count_; } } SmartPointer<T>& operator=(const SmartPointer<T>& other) { if (this != &other) { if (--(*ref_count_) == 0) { delete ptr_; delete ref_count_; } ptr_ = other.ptr_; ref_count_ = other.ref_count_; ++(*ref_count_); } return *this; } T& operator*() const { return *ptr_; } T* operator->() const { return ptr_; } private: T* ptr_; size_t* ref_count_; }; int main() { SmartPointer<int> sp1(new int(5)); std::cout << *sp1 << std::endl; SmartPointer<int> sp2 = sp1; std::cout << *sp2 << std::endl; sp1 = SmartPointer<int>(new int(10)); std::cout << *sp1 << std::endl; std::cout << *sp2 << std::endl; return 0; } ``` 在上面的例子中,我们定义了一个模板类 SmartPointer,它保存了一个指向动态分配内存的原始指针 ptr_,以及一个引用计数 ref_count_。构造函数中,我们将引用计数初始化为1。当拷贝构造一个智能指针时,我们增加引用计数。当析构一个智能指针时,我们减少引用计数,并在引用计数变为0时释放内存。赋值运算符重载中,我们首先减少旧指针的引用计数,然后增加新指针的引用计数。 这只是一个简单智能指针实现示例,实际上,标准库中的std::shared_ptr和std::unique_ptr提供了更多的功能和安全性保证。但是这个实现可以帮助你理解智能指针的基本原理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值