如何在C++中使用标准库的智能指针

使用标准库的智能指针

* 注意,在使用数组的时候需要使用数组的特化版本。

复制代码
#include <iostream>
#include <memory>

std::unique_ptr<char[]> division(int x, int y) {
    std::unique_ptr<char[]> sp(new char[100]{});
    if (y == 0) {
        throw "Please do not use 0 as a divisor";
    }
    std::sprintf(sp.get(), "%d / %d = %d\n", x, y, x / y);
    return sp;
}

int main() {
    try {
        std::unique_ptr<char[]> sp = division(6, 0);
        std::cout << sp.get() << std::endl;
    } catch (const char* e) {
        std::cerr << e << std::endl;
    }
}

互斥锁的释放

在多线程编程中,为了保护共享资源,我们通常会使用 互斥量 mutex 来进行保护。

并且在使用资源前进行上锁的 lock() 操作,在使用完毕后用 unlock() 进行解锁。

直接使用互斥量

这里假定在 2000ms 后两个线程都会结束。

复制代码
#include <iostream>
#include <thread>
#include <mutex>

int x = 0;
std::mutex mutex;

void fun() {
    for (int i = 0; i < 100000; i += 1) {
        mutex.lock();
        x += 1;
        mutex.unlock();
    }
}

int main() {
    std::thread th1(fun);
    std::thread th2(fun);
    th1.join();
    th2.join();

    std::cout << x << std::endl;
}

但是这种写法需要开始和结束处都对 mutex 整个对象进行操作。此处代码较短不容易出错,但是当代码量越来越大,各种情况越来越复杂后就很容易遗漏最后的 mutex.unlock(); 解锁操作。

此时就可以使用 RAII 的方式,在构造的时候对 mutex 进行 lock() 操作,在 unlock() 进行解锁操作。

相关推荐
好好学习O(∩_∩)O17 分钟前
[QT] 多线程moveToThread 和易踩的8个坑
开发语言·qt
Gigavision33 分钟前
DEAP数据集 2026最新Transformer算法 DEAP 数据集 下载
深度学习·算法·transformer
我是人✓35 分钟前
Java核心语法:作用域、循环与大数值处理
java·开发语言·后端
敲代码的乔帮主39 分钟前
Python 3 现代类型标注入门
开发语言·python
夜之眷属1 小时前
PriorityQueue:for-each 遍历和 poll 取出,顺序一样吗?
java·服务器·数据结构·后端·算法
‎ദ്ദിᵔ.˛.ᵔ₎1 小时前
c++11:fuction包装器
开发语言·c++
kimnoic1 小时前
Python 爬虫的原理
开发语言·python
Fluxproxy1 小时前
Python爬虫异步提速终极方案|线程池ThreadPoolExecutor实战,告别单线程慢速爬取
开发语言·爬虫·python
地平线开发者2 小时前
不是线程越多越快:用 hrt_model_exec 在 征程6M 上给 YOLOv5x 建立性能基线
算法
淡海水2 小时前
02-07-原理篇-GC暂停时间的本质
开发语言·unity·c#·gc·暂停时间