C++智能指针shared_ptr

简介: C++智能指针shared_ptr

C++智能指针shared_ptr

学习路线:C++智能指针shared_ptr->C++智能指针unique_ptr->C++智能指针weak_ptr

简介:本文讲解常用的智能指针的用法和原理,包括shared_ptr,unique_ptr,weak_ptr。

shared_ptr

概述

shared_ptr(共享指针),对于同一个Object,共享指针会记录有多少个指针指向同一个物体,当指向Object的指针计数为0的时候,Object对象就会释放,省去了delete的烦恼。

使用方法

  • 引用头文件
#include<memory>  // 引入头文件
using namespace std;
  • 定义方法
// 方式一 推荐
shared_ptr<int> p = make_shared<int>(100);
// 方式二
shared_ptr<int> p = new int(100);

自动管理内存

学习代码

#include<memory>
#include<iostream>
using namespace std;
class Ball
{
    public:
        Ball(){
            cout << "A ball construct." << endl;
        }
        ~Ball(){
            cout << "A ball disconstruct" << endl;
        }
        void Jump(){
            cout << "A ball jump" << endl;
        }
};
int main()
{
    shared_ptr<Ball> p = make_shared<Ball>();
    cout << p.use_count() << endl;
    shared_ptr<Ball> p2 = p;
    cout << p.use_count() << " " << p2.use_count() << endl;
    shared_ptr<Ball> p3 = p;
    cout << p.use_count() << " " << p2.use_count() << " "
         << p3.use_count() << endl;
    p.reset();
    p2.reset();
    p3.reset();
    return 0;
}

运行结果:

分析结果可知:

当指向最开始的对象Ball的指针都释放了之后,那么最开始的对象Ball也会被释放。

合并集合

一共有 n 个数,编号是 1∼n,最开始每个数各自在一个集合中。

现在要进行 m 个操作,操作共有两种:

M a b,将编号为 a 和 b 的两个数所在的集合合并,如果两个数已经在同一个集合中,则忽略这个操作;

Q a b,询问编号为 a 和 b 的两个数是否在同一个集合中;

输入格式

第一行输入整数 n 和 m。

接下来 m 行,每行包含一个操作指令,指令为 M a b 或 Q a b 中的一种。

输出格式

对于每个询问指令 Q a b,都要输出一个结果,如果 a 和 b 在同一集合内,则输出 Yes,否则输出 No。

每个结果占一行。

数据范围

1≤n,m≤105

输入样例:

4 5

M 1 2

M 3 4

Q 1 2

Q 1 3

Q 3 4

输出样例:

Yes

No

Yes

提交代码

#include<iostream>
using namespace std;
const int N = 100010;
int n, m;
int p[N];
int find(int x)                 // 找到x的祖先节点
{
    if (p[x] != x) p[x] = find(p[x]);
    return p[x];
}
int main()
{
    scanf("%d %d", &n, &m);
    for (int i = 1; i <= n; ++i) p[i] = i;
    while (m--)
    {
        char op;
        int a, b;
        scanf (" %c%d%d", &op, &a, &b);
        if (op == 'M') p[p[find(a)]] = find(b);        // 让a的祖先节点指向b的祖先节点
        else
        {
            if (find(a) == find(b)) puts("Yes");
            else puts("No");
        }
    }
    return 0;
}
import java.io.*;
public class Main
{
    static int N = 100010;
    static int n, m;
    static int [] p = new int [N];
    static int find(int x)
    {
        if (p[x] != x) p[x] = find(p[x]);
        return p[x];
    }
    public static void main(String[] args) throws IOException
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader (System.in));   
        String [] str = reader.readLine().split(" ");
        n = Integer.parseInt(str[0]);
        m = Integer.parseInt(str[1]);
        for (int i = 1; i <= n; ++ i) p[i] = i;
        while (m -- > 0)
        {
            String op;
            int a, b;
            str = reader.readLine().split(" ");
            op = str[0];
            a = Integer.parseInt(str[1]);
            b = Integer.parseInt(str[2]);
            if (op.equals("M")) p[find(a)] = find(b);
            else 
            {
                if (find(a) == find(b)) System.out.println("Yes");
                else System.out.println("No");
            }
        }
    }
}
相关文章
|
24天前
|
存储 Java C++
C++ 引用和指针:内存地址、创建方法及应用解析
C++中的引用是现有变量的别名,创建时需用`&`运算符,如`string &meal = food;`。指针存储变量的内存地址,使用`*`创建,如`string* ptr = &food;`。引用必须初始化且不可为空,而指针可初始化为空。引用在函数参数传递和提高效率时有用,指针适用于动态内存分配和复杂数据结构操作。选择使用取决于具体需求。
38 9
|
25天前
|
存储 安全 编译器
【C++专栏】C++入门 | auto关键字、范围for、指针空值nullptr
【C++专栏】C++入门 | auto关键字、范围for、指针空值nullptr
29 0
|
4天前
|
C++
【C++】一文深入浅出带你参透库中的几种 [ 智能指针 ]及其背后实现原理(代码&图示)
【C++】一文深入浅出带你参透库中的几种 [ 智能指针 ]及其背后实现原理(代码&图示)
|
12天前
|
C++
【C++11(三)】智能指针详解--RAII思想&循环引用问题
【C++11(三)】智能指针详解--RAII思想&循环引用问题
|
12天前
|
人工智能 C++
【重学C++】【指针】轻松理解常量指针和指针常量
【重学C++】【指针】轻松理解常量指针和指针常量
12 0
|
12天前
|
存储 人工智能 C++
【重学C++】【指针】详解让人迷茫的指针数组和数组指针
【重学C++】【指针】详解让人迷茫的指针数组和数组指针
29 1
|
12天前
|
存储 人工智能 编译器
【重学C++】【指针】一文看透:指针中容易混淆的四个概念、算数运算以及使用场景中容易忽视的细节
【重学C++】【指针】一文看透:指针中容易混淆的四个概念、算数运算以及使用场景中容易忽视的细节
19 1
|
19天前
|
存储 编译器 C++
【C++成长记】C++入门 | 类和对象(上) |类的作用域、类的实例化、类的对象大小的计算、类成员函数的this指针
【C++成长记】C++入门 | 类和对象(上) |类的作用域、类的实例化、类的对象大小的计算、类成员函数的this指针
|
26天前
|
存储 编译器 程序员
【C++】类和对象①(什么是面向对象 | 类的定义 | 类的访问限定符及封装 | 类的作用域和实例化 | 类对象的存储方式 | this指针)
【C++】类和对象①(什么是面向对象 | 类的定义 | 类的访问限定符及封装 | 类的作用域和实例化 | 类对象的存储方式 | this指针)
|
10天前
|
C语言
C语言:数组和指针笔试题解析(包括一些容易混淆的指针题目)
C语言:数组和指针笔试题解析(包括一些容易混淆的指针题目)