C++智能指针

学习视频
库存库存~

智能指针概述

C++的指针包括原始指针和智能指针两种,智能指针是原始指针的封装,其优点是可以自动分配内存,无需担心内存的泄露。

  • 并不是所有的指针都可以封装为智能指针,很多时候原始指针要更方便;

  • 各种指针里,原始指针最常用,其次是unique_ptr和shared_ptr,weak_ptr是对shared_ptr的补充,应用场景较少。

  • 智能指针只能解决一部分问题:独占/共享所有权指针的释放和传输;并没有从根本上解决C++的内存泄漏问题(Rust)

独占指针 unique_ptr

在给定的时刻,只能有一个指针管理内存

当指针超出作用域后,内存自动释放

该类型指针不可Copy,只可以Move

创建方式

  • 通过已有的裸指针创建(建议裸指针设为空,并且及时销毁)
  • 通过new创建
  • 通过std::make_unique创建(推荐

unique_str可以通过get获取地址,通过->调用成员函数,通过*调用dereferencing(解引用)

测试代码


#include "cat.h"


cat::cat(std::string name):name(name){
    std::cout<<"Constructor of Cat: "<<name<<std::endl;
}

cat::~cat(){
    std::cout<<"Destructor of Cat: "<<name<<std::endl;
}



#ifndef PTR_CAT_H
#define PTR_CAT_H
#include<string>
#include<iostream>

class cat {
public:
    cat(std::string name);
    cat()=default;
    ~cat();
    void cat_info()const{
        std::cout<<"cat info name: "<< name <<std::endl;
    }
    std::string get_name()const{
        return name;
    }
    void set_cat_name(const std::string &name){
        this->name=name;
    }
private:
    std::string name{"Mini"};
};


#endif //PTR_CAT_H

#include <iostream>
#include <memory>
#include "unique/cat.h"

int main() {
    //栈上 自动销毁 没有用到指针
//    cat c1("stack");
//    c1.cat_info();
//    {
//        cat c1("stack1");
//        c1.cat_info();
//    }
    /*
     * Constructor of Cat: stack
cat info name: stack
Constructor of Cat: stack1
cat info name: stack1
Destructor of Cat: stack1
end
Destructor of Cat: stack
     * */

//普通指针 不会销毁 需要自己调用delete pc1
//    cat* pc1=new cat("ok");
//    pc1->cat_info();
//    {
//        cat* pc1=new cat("ok");
//        pc1->cat_info();
//    }
/*
 * Constructor of Cat: ok
cat info name: ok
Constructor of Cat: ok
cat info name: ok
end
 */
//智能指针 第一种构建方式
//    cat* pc2=new cat("ok");
//    std::unique_ptr<cat> ucp1{pc2};
//    ucp1->cat_info();
//    pc2->cat_info();
//    pc2->set_cat_name("abc");
//    ucp1->cat_info();//不满足独占指针的独占性质了
    //要及时delete pc2
    /*Constructor of Cat: ok
cat info name: ok
cat info name: ok
cat info name: abc
end
Destructor of Cat: abc
     * */
    //智能指针 第二种构建方式
//    std::unique_ptr<cat> ucp2{new cat("ok")};
//    ucp2->cat_info();
//    ucp2->set_cat_name("aa");
//    ucp2->cat_info();
    /*Constructor of Cat: ok
cat info name: ok
cat info name: aa
end
Destructor of Cat: aa
     * */
    //智能指针 第三种方式 推荐
    std::unique_ptr<cat>ucp3=std::make_unique<cat>();
    ucp3->cat_info();
    ucp3->set_cat_name("now");
    ucp3->cat_info();
    std::cout<<"cat address: "<<ucp3.get()<<std::endl;
    /*
     cat info name: Mini
cat info name: now
cat address: 0x213c24418c0
end
Destructor of Cat: now
     * */
    std::cout << "end" << std::endl;
    return 0;
}

独占指针和函数调用

注意独占指针的所有权

  • pass by value
    • 通过std::move来转移内存拥有权
    • 如果参数传入的是std::make_unique语句,自动转化为move
  • pass by reference
    • 如果参数设置为const则不能改变指向,比如不能调用reset
  • return by value
    • 链式函数
#include <iostream>
#include <memory>
#include "unique/cat.h"

void do_with_cat_pass_value(std::unique_ptr<cat>c){
    c->cat_info();
}

void do_with_cat_pass_ref(const std::unique_ptr<cat>&c){ //常用
    c->set_cat_name("oo");
    c->cat_info();
  //  c.reset();//清空
}

std::unique_ptr<cat> get_unique_ptr(){
    std::unique_ptr<cat>p=std::make_unique<cat>("local cat");
    return p;
}

int main() {
//    //1.pass by value
//    std::unique_ptr<cat>c1= std::make_unique<cat>("ff");
//    do_with_cat_pass_value(std::move(c1));
//    //c1->cat_info //不可以执行
//    do_with_cat_pass_value(std::make_unique<cat>());

//    Constructor of Cat: ff
//    cat info name: ff
//    Destructor of Cat: ff
//    cat info name: Mini
//    Destructor of Cat: Mini
//    end

    //2.pass by ref
//    std::unique_ptr<cat>c2=std::make_unique<cat>("f2");
//    do_with_cat_pass_ref(c2);
//    c2->cat_info();//已经被reset了,不能调用
//    std::cout<<"cat address: "<<c2.get()<<std::endl;

//    Constructor of Cat: f2
//    cat info name: oo
//    cat info name: oo
//    cat address: 0x1e97a8318c0
//    end
//    Destructor of Cat:
    //3.链式




    std::cout << "end" << std::endl;
    return 0;
}

计数指针

可以共享数据

创建了一个计数器,和类对象所指的内存相关联,Copy则计数器加一,销毁则计数器减一,通过use_count调用

#include <iostream>
#include <memory>
#include "unique/cat.h"

using namespace std;

int main() {
    //1.常量类型
    shared_ptr<int>ip1= make_shared<int>(100);
    cout<<"value: "<<*ip1<<endl;
    cout<<"use count: "<<ip1.use_count()<<endl;

    //copy
    shared_ptr<int>ip2=ip1;
    cout<<"ip1 use count: "<<ip1.use_count()<<endl;
    cout<<"ip2 use count: "<<ip2.use_count()<<endl;

    //change
    *ip2=300;
    cout<<"ip1 value: "<<*ip1<<endl;
    cout<<"ip2 value: "<<*ip2<<endl;

    shared_ptr<int>ip3=ip1;
    ip2= nullptr;
    cout<<"ip1 use count: "<<ip1.use_count()<<endl;
    cout<<"ip2 use count: "<<ip2.use_count()<<endl;
    cout<<"ip3 use count: "<<ip3.use_count()<<endl;

//    value: 100
//    use count: 1
//    ip1 use count: 2
//    ip2 use count: 2
//    ip1 value: 300
//    ip2 value: 300
//    ip1 use count: 2
//    ip2 use count: 0
//    ip3 use count: 2
//    end
    
    std::cout << "end" << std::endl;
    return 0;
}

#include <iostream>
#include <memory>
#include "unique/cat.h"

using namespace std;

int main() {
    //2.自定义类型
    shared_ptr<cat>cp1= make_shared<cat>();
    cout<<"cp1 use count: "<<cp1.use_count()<<endl;

    shared_ptr<cat>cp2=cp1;
    shared_ptr<cat>cp3=cp1;

    cout<<"cp1 use count: "<<cp1.use_count()<<endl;
    cout<<"cp2 use count: "<<cp2.use_count()<<endl;
    cout<<"cp3 use count: "<<cp3.use_count()<<endl;

    cp1.reset();
    cout<<"cp1 use count: "<<cp1.use_count()<<endl;
    cout<<"cp2 use count: "<<cp2.use_count()<<endl;
    cout<<"cp3 use count: "<<cp3.use_count()<<endl;


//    cp1 use count: 1
//    cp1 use count: 3
//    cp2 use count: 3
//    cp3 use count: 3
//    cp1 use count: 0
//    cp2 use count: 2
//    cp3 use count: 2
//    end
//    Destructor of Cat: Mini
    
    std::cout << "end" << std::endl;
    return 0;
}

共享指针和函数

  • pass by value
    • copy的形式
    • 函数内部计数器+1
  • pass by ref
    • const表示不可改变指向
  • return by value
    • 链式调用
#include <iostream>
#include <memory>
#include "unique/cat.h"

using namespace std;

void cat_pass_by_value(shared_ptr<cat> cp){
    cout<<cp->get_name()<<endl;
    cp->set_cat_name("bb");
    cout<<"func use count : "<<cp.use_count()<<endl;
}

void cat_pass_by_ref(shared_ptr<cat> &cp){
    cout<<cp->get_name()<<endl;
    cp->set_cat_name("ee");
    cp.reset(new cat());
    cout<<"func use count : "<<cp.use_count()<<endl;
}


int main() {
     shared_ptr<cat> c1= make_shared<cat>();
//    cat_pass_by_value(c1);
//    c1->cat_info();
//    cout<<"main use count : "<<c1.use_count()<<endl;

//    Mini
//    func use count : 2
//    cat info name: bb
//    main use count : 1
//    end
//    Destructor of Cat: bb

    cat_pass_by_ref(c1);
    c1->cat_info();
    cout<<"main use count : "<<c1.use_count()<<endl;

//    Destructor of Cat: ee
//    func use count : 1
//    cat info name: Mini
//    main use count : 1
//    end
//    Destructor of Cat: Mini

    std::cout << "end" << std::endl;
    return 0;
}

shared_ptr vs unique_ptr

不能将shared_ptr转为unique_ptr

unique_ptr可以通过move转为shared_ptr

weak_ptr

不拥有所有权,不调用->和解引用*

A类需要存储B类的信息,B类也存储了A类的信息,销毁的时候不知道先销毁哪个,循环依赖问题。

wak_ptr可以通过lock函数提升为shared_ptr

修改cat.h


#ifndef PTR_CAT_H
#define PTR_CAT_H
#include<string>
#include<iostream>
#include<memory>

class cat {
public:
    cat(std::string name);
    cat()=default;
    ~cat();
    void cat_info()const{
        std::cout<<"cat info name: "<< name <<std::endl;
    }
    std::string get_name()const{
        return name;
    }
    void set_cat_name(const std::string &name){
        this->name=name;
    }
    void set_friend(std::shared_ptr<cat> c){
        m_friend=c;
    }
private:
    std::string name{"Mini"};
    std::weak_ptr<cat>m_friend;
};


#endif //PTR_CAT_H

#include <iostream>
#include <memory>
#include "unique/cat.h"

using namespace std;



int main() {
     shared_ptr<cat> c1= make_shared<cat>("c1");
     shared_ptr<cat> c2= make_shared<cat>("c2");
     c1->set_friend(c2);
     c2->set_friend(c1);
//循环依赖 无法销毁 设置为shared_ptr
//必须设置为weak_ptr
//    Constructor of Cat: c1
//    Constructor of Cat: c2
//    end


    std::cout << "end" << std::endl;
    return 0;
}

Constructor of Cat: c1
Constructor of Cat: c2
end
Destructor of Cat: c2
Destructor of Cat: c1
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C++智能指针是一种用于管理动态分配的内存资源的工具。C++中提供了多种类型的智能指针,其中包括shared_ptr、unique_ptr和weak_ptr。这些智能指针都位于头文件<memory>中。 其中,shared_ptr是一种引用计数智能指针,它允许多个智能指针共享同一个对象。shared_ptr通过对对象的引用计数来管理内存的释放,当引用计数为0时,即没有智能指针指向该对象时,对象会被自动释放。使用shared_ptr需要包含头文件<memory>,并通过new关键字创建动态分配的对象并将其交给shared_ptr进行管理。 另一种智能指针是unique_ptr,它是一种独占型智能指针,只能有一个智能指针拥有对对象的所有权。当unique_ptr对象被销毁时,它所管理的对象也会被自动释放。unique_ptr提供了更高效的内存管理方式,因为它不需要进行引用计数。使用unique_ptr也需要包含头文件<memory>,并使用new关键字创建动态分配的对象并将其交给unique_ptr进行管理。 除了shared_ptr和unique_ptr,还有其他类型的智能指针,如weak_ptr和scoped_ptr。weak_ptr是一种弱引用智能指针,它用于解决shared_ptr可能出现的循环引用问题。scoped_ptr是一种简单的智能指针,它只能在创建时初始化,并且不能进行复制和赋值操作。scoped_ptr在其所属的作用域结束时自动释放所管理的对象。 总结起来,C++智能指针是一种用于管理动态分配的内存资源的工具,包括shared_ptr、unique_ptr、weak_ptr和scoped_ptr等类型。它们提供了一种更安全、更高效的内存管理方式,避免了手动释放内存的麻烦。要使用这些智能指针,需要包含头文件<memory>,并通过new关键字创建动态分配的对象并将其交给相应的智能指针进行管理。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [C++ -- 智能指针C++11与boost库的智能指针及其使用)](https://blog.csdn.net/xu1105775448/article/details/80625936)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [C++智能指针的底层实现原理](https://blog.csdn.net/ArtAndLife/article/details/120793343)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豆沙睡不醒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值