如何在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() 进行解锁操作。

相关推荐
code2cat14 小时前
【随笔】Java客户端选了HTTP/3,怎样知道请求实际走了哪个版本
java·开发语言·http
cjz389914 小时前
双指针技巧:覆盖式双指针(原地覆盖)
算法
whitelbwwww14 小时前
cuBLAS--CUDA高性能线性代数计算库--第一部分
c++·线性代数·gpu算力·cuda c++
honker_X16 小时前
Python字符串全攻略:从入门到精通
开发语言·python
半杯咖啡半行码16 小时前
Qt 隐式共享(Implicit Sharing)深度解析:机制、陷阱与 Qt6迁移
开发语言·数据库·qt
吃我一窝jio17 小时前
Docker+Jenkins+K8s全流程部署
java·开发语言·笔记·python
eggwyw17 小时前
C++设计模式之解释器模式
开发语言·c++
橘子1318 小时前
【高级数据库】关系代数基本概念
算法
mengge.cloud19 小时前
Python基础保姆级!从入门到入土
开发语言·python·云原生·pygame
在爪洼山玩泥巴20 小时前
fastjson2 JSONPath 取不存在路径,为什么会抛 “not support”?
java·开发语言·jsonpath·fastjson