c++智能指针

2021/8/3 22:07:57

本文主要是介绍c++智能指针,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

种类

  1. unique_ptr
  2. shared_ptr
  3. weak_ptr

shared_ptr实现

参考:https://www.jianshu.com/p/b6ac02d406a0
引用计数托管指针被引用的次数

简单实现:

#include <iostream>

using namespace std;

template<class T>

class shared_ptr{

private:

T* m_ptr; //被封装的指针

unsigned int shared_count;   //引用计数,表示有多少个智能指针对象拥有m_ptr指向的内存块

public:

shared_ptr(T* p):m_ptr(p),shared_count(1){ }

~shared_ptr() { deconstruct();}

void deconstruct(){

if(shared_count == 1)   //引用计数为1表示只有一个对象使用指针指向的内存块了

{

delete m_ptr;

m_ptr = 0;

}

shared_count--;

}

T& operator*() { return *m_ptr;}

T* operator->() { return m_ptr;}

 

//复制构造函数

shared_ptr(shared_ptr& sp):m_ptr(sp.m_ptr),shared_count(sp.shared_count){

shared_count++;

}

//重载运算符=

shared_ptr& operator = (shared_ptr& sp){

sp.shared_count++;   

deconstruct();  //相当于先删掉左值,然后再通过右值赋值.

m_ptr = sp.m_ptr;

shared_count = sp.shared_count;

return *this;

} 

};


这篇关于c++智能指针的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程