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

相关推荐
WWTYYDS_6661 分钟前
JsonCpp超详细使用教程
c++
不会就选b8 分钟前
算法日常・每日刷题--<快排>4
算法
Keven_1114 分钟前
算法札记:树状数组的用途
数据结构·算法
Joey_friends18 分钟前
指纹authenticate流程图
android·java·c++
用户6774371758120 分钟前
C++函数参数传递方式详解:string、string&、const string、const string&该怎么选?
算法
Helen_cai31 分钟前
OpenHarmony 项目统一全局样式、尺寸、色彩主题封装 ThemeUtil(API23)
开发语言·前端·javascript·华为·harmonyos
郑州光合科技余经理32 分钟前
家政O2O平台解析:从0搭建上门预约小程序解决方案
android·java·开发语言·前端·小程序·架构·php
cpp_25011 小时前
P1540 [NOIP 2010 提高组] 机器翻译
数据结构·c++·算法·队列·noip·洛谷题解
晚笙coding1 小时前
LeetCode 98:验证二叉搜索树 —— 从局部判断到全局范围约束的递归思想
算法·leetcode·职场和发展
深念Y1 小时前
开发者如何清理和迁移C盘堆积的垃圾
c语言·开发语言