C++智能指针

简介: 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天前
|
C++ 编译器
|
2天前
|
C++ 数据格式
LabVIEW传递接收C/C++DLL指针
LabVIEW传递接收C/C++DLL指针
10 1
|
3天前
|
存储 安全 程序员
C++:智能指针
C++:智能指针
19 5
|
4天前
|
存储 安全 C++
深入理解C++中的指针与引用
深入理解C++中的指针与引用
7 0
|
5天前
|
算法 C++
【C++入门到精通】智能指针 shared_ptr循环引用 | weak_ptr 简介及C++模拟实现 [ C++入门 ]
【C++入门到精通】智能指针 shared_ptr循环引用 | weak_ptr 简介及C++模拟实现 [ C++入门 ]
10 0
|
5天前
|
安全 算法 数据安全/隐私保护
【C++入门到精通】智能指针 shared_ptr 简介及C++模拟实现 [ C++入门 ]
【C++入门到精通】智能指针 shared_ptr 简介及C++模拟实现 [ C++入门 ]
10 0
|
5天前
|
存储 算法 安全
【C++入门到精通】智能指针 auto_ptr、unique_ptr简介及C++模拟实现 [ C++入门 ]
【C++入门到精通】智能指针 auto_ptr、unique_ptr简介及C++模拟实现 [ C++入门 ]
9 0
|
5天前
|
安全 算法 IDE
【C++入门到精通】智能指针 [ C++入门 ]
【C++入门到精通】智能指针 [ C++入门 ]
8 0
|
6天前
|
存储 编译器 C语言
【C++】类与对象【定义、访问限定符、this指针】
【C++】类与对象【定义、访问限定符、this指针】
6 1
|
11天前
|
C++
【C++】一文深入浅出带你参透库中的几种 [ 智能指针 ]及其背后实现原理(代码&图示)
【C++】一文深入浅出带你参透库中的几种 [ 智能指针 ]及其背后实现原理(代码&图示)