C++内存管理详解

C语言的内存管理交予用户。所以现在C语言的内存管理要靠用户的良好编码习惯。当然现在一般成熟的语言都有GC机制,即为垃圾回收机制。共同基类管理,内部加引用计数都可以实现GC机制。
在这里插入图片描述
但是C++没有GC机制,最主要是没有共同基类,其次是垃圾回收机制占用系统开销降低性能,并且需要占用更多的内存。C++使用析构函数或者智能指针引用计数去管理内存资源的释放。

智能指针

**作用:**帮助开发者对动态分配对象(new)的生命周期进行管理。能够有效防止内存泄漏。
**头文件:**memory
分类:

  • auto_ptr(C++98):被C++11智能指针替代,不再使用
  • unique_ptr(C++11): 独占指针
  • shared_ptr(C++11):共享指针
  • weak_ptr(C++11):弱指针

shared_ptr

#include <iostream>
#include <memory>
using namespace std;
class Test{
public:
    Test(){
        cout << "Test()" << endl;
    }
    ~Test(){
        cout << "~Test()" << endl;
    }
    friend ostream &operator<<(ostream &out , const Test &t){
        out  << "Test";
        return out;
    }
};
using namespace std;
int main(){
    //shared_ptr
    int num = 5;

    //C++11
    shared_ptr<int> pi(new int (5));
    int *p = new int(4);
    shared_ptr<int> pi2(p);     //共享指针包裹
    shared_ptr<Test> pt(new Test());
    cout << *pi << endl;
    cout << *pi2 << endl;
    cout << *pt << endl;

    //C++14     推荐该方法,效率更高
    shared_ptr<string> ps = std::make_shared<string>("hello world");
    shared_ptr<int> pi3 = std::make_shared<int>(1);
    return 0;
}

方法:

//use_count() :返回有多少个shared_ptr智能指针指向某对象;(引用计数的个数)
//unique():是否该智能指针独占某个对象,独占返回true,否则返回false;
//reset():

shared_ptr<int> pi(new int (5));
shared_ptr<int> pi1 = pi;          //裸指针int *
shared_ptr<int> pi2 = pi1;
cout << pi.use_count() << endl;    //输出3
pi.reset();
if(pi == nullptr){
    cout << "pui is null" << endl;    //会执行
}
pi.reset(new int(6));    //重新指向新地址
    
//get():考虑到有些函数参数是裸指针并不是智能指针,所以需要将智能指针转化为裸指针;
    int *p = pi.get();    //因为现在pi中存的是int。   
//对于裸指针有时候要注意,例如下句会执行报错,程序默认裸指针为Test*而只调用一次析构函数。
shared_ptr<Test> pt(new Test[3]);   
//修改:
shared_ptr<Test []> pt(new Test[3]);  

//指定删除器 
void mydelete(Test *pa){
    cout << "my delete" << endl;
    delete [] pa;
}

shared_ptr<Test> ps(new Test [3] , mydelete);

weak_ptr

一般用来辅助shared_ptr的使用,shared_ptr可以复制给weak_ptr,反过来不行,需要lock()

与shared_ptr的强引用不同的是,它是弱引用。
两者大小都是16,因为本质是两个指针,一个指向对象,一个是指向控制块。

shared_ptr<int> pi(new int (5));
weak_ptr<int> pw = pi;

//lock函数获得shared_ptr(若对象已经被释放,则返回空)
pi = pw.lock();
//use_count():返回有多少个shared_ptr指向某对象
//expired():判断弱指针是否过期(所检测的对象是否被释放 true/false)
//reset():将该弱指针设置为空,弱引用计数减1,强引用计数不变

unique_ptr
独占式指针(专属所有权),同一时刻,只能有一个unique_ptr指向这个对象;当指针销毁,指向的对象也销毁;大小等于裸指针的大小。

初始化
手动初始化:unique_ptr p;
或unique p(new int(5));
std::make_unique函数(C++14) 注:生成的指针不支持指定删除器语法

unique_ptr常规操作
不支持操作:该指针不支持拷贝和赋值操作;所以函数传参必须传引用。
移动语义std::move();
release():放弃对指针的控制权,将该指针置nullptr,返回裸指针。
reset();
解引用:get():返回裸指针。
指定删除器
语法:unique_ptr<指向对象类型,删除器的类型> 智能指针变量名
自定义删除函数
lambda函数
decltype()
指定不同的删除器会导致不同的unique_ptr;

shared_ptr指定不同的删除器不会影响其类型;而unique_ptr 会。
比如定义一个vector存放,会发现不同删除器的指针不同都push_back()。
unique_ptr尺寸:和裸指针一样大,但是指定自定义删除函数会影响尺寸大小;

作业:实现shared_ptr

//my_shared_ptr.h
#pragma once
#include <iostream>
using namespace std;

template <typename T>
class My_shared_ptr
{
private:
    T *ptr;
    int *count_ptr;
    using Del_ptr = void (*)(T*);
    Del_ptr del = nullptr;
public: 

    My_shared_ptr() : ptr((T *) 0) , count_ptr(0)  {}

    My_shared_ptr(T *data) : ptr(data) , count_ptr(new int(1)) {
        cout << "My_shared_ptr" << endl;
    }

    My_shared_ptr(T *data , Del_ptr func) : ptr(data) , count_ptr(new int(1)) , del(func) {
        cout << "My_shared_ptr with my_del" << endl;
    }

    My_shared_ptr(const My_shared_ptr<T> &other_ptr){
        cout << "copy My_shared_ptr" << endl;
        if(this != &other_ptr){
            this->ptr = other_ptr.ptr;
            this->count_ptr = &(++ *other_ptr.count_ptr);
            this->del = other_ptr.del;
        }
    }

    My_shared_ptr &operator=(const My_shared_ptr<T> &other_ptr){
        cout << "operator =" << endl;
        if(this == &other_ptr)
            return *this;
        ++ *other_ptr.count_ptr;
        if(-- *this->count_ptr == 0){
            delete ptr;
            delete count_ptr;
        }
        this->ptr = other_ptr.ptr;
        this->count_ptr = other_ptr.count_ptr;
        this->del = other_ptr.del;
        return *this;
    }

    ~My_shared_ptr(){
        cout << "~My_shared_ptr()" << endl;
        if(-- *this->count_ptr == 0){
            if(this->del){
                this->del(this->ptr);
            }
            else{
                delete ptr;
                delete count_ptr;
            }
        }
        this->ptr = nullptr;
        this->count_ptr = nullptr;
    }

    int get_count(){
        return *this->count_ptr;
    }

    bool unique(){
        if(*this->count_ptr == 1)
            return true;
        else
            return false;
    }

    T &operator*(){
        return *this->ptr;
    }

    T *get(){
        return this->ptr;
    }

    void reset(){
        if(-- *this->count_ptr == 0){
            delete ptr;
            delete count_ptr;
        }
    }

    void reset(T *data){
        if(-- *this->count_ptr == 0){
            delete ptr;
            delete count_ptr;
        }
        this->ptr = data;
        this->count_ptr = new int(1);
    }

    void reset(T *data , Del_ptr func){
        if(-- *this->count_ptr == 0){
            delete ptr;
            delete count_ptr;
        }
        this->ptr = data;
        this->count_ptr = new int(1);
        this->del = func;
    }
};

//test.cpp
#include <iostream>
#include "my_shared_ptr.h"
using namespace std;
class Test{
public:
    Test(){
        cout << "Test()" << endl;
    }
    ~Test(){
        cout << "~Test()" << endl;
    }
};
void mydelete(Test *pa){
    cout << "my delete" << endl;
    delete [] pa;
}

int main(){
    My_shared_ptr<string> pstr(new string("hello world"));
    My_shared_ptr<string> pstr1 = pstr;

    cout << "值:" << endl;
    cout << *pstr << endl;
    cout << *pstr1 << endl;

    cout << "引用数量:" << endl;
    cout << pstr.get_count() << endl;
    cout << pstr1.get_count() << endl;

    cout << "转化为普通指针输出:" << endl;
    string *s = pstr.get();
    cout << *s << endl;

    cout << "第二个智能指针重新赋地址:" << endl;
    pstr1.reset(new string("a new string"));
    cout << *pstr1 << endl;

    cout << "更改后的引用数量:" << endl;
    cout << pstr.get_count() << endl;
    
    My_shared_ptr<Test> pi(new Test[3] , mydelete);
    return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值