C++11 新特性:智能指针的使用与解析

C++11 新特性:智能指针的使用与解析

在现代 C++ 编程中,智能指针是管理动态内存的利器,它可以有效避免内存泄漏和悬空指针问题。本文将介绍 C++11 中的三种智能指针:unique_ptrshared_ptrweak_ptr,并给出使用示例。


一、unique_ptr

unique_ptr 表示独占所有权,一个对象在任意时刻只能有一个 unique_ptr 拥有它。

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

class Test {
public:
    Test() { std::cout << "Test 构造\n"; }
    ~Test() { std::cout << "Test 析构\n"; }
    void hello() { std::cout << "Hello from Test\n"; }
};

int main() {
    std::unique_ptr<Test> ptr1 = std::make_unique<Test>();
    ptr1->hello();

    // std::unique_ptr<Test> ptr2 = ptr1; // 错误,不能拷贝
    std::unique_ptr<Test> ptr2 = std::move(ptr1); // 转移所有权
    if (!ptr1) std::cout << "ptr1 已经为空\n";
}

二、shared_ptr

shared_ptr 是共享所有权的智能指针,可以多个 shared_ptr 指向同一个对象,对象会在最后一个 shared_ptr 销毁时释放。

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

int main() {
    std::shared_ptr<int> sp1 = std::make_shared<int>(42);
    std::shared_ptr<int> sp2 = sp1;

    std::cout << "sp1 use_count: " << sp1.use_count() << "\n"; // 2
    std::cout << "sp2 value: " << *sp2 << "\n";
}

三、weak_ptr

weak_ptr 弱引用 shared_ptr 管理的对象,不增加引用计数,用于解决循环引用问题。

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

int main() {
    std::shared_ptr<int> sp = std::make_shared<int>(100);
    std::weak_ptr<int> wp = sp;

    std::cout << "sp use_count: " << sp.use_count() << "\n"; // 1
    if (auto tmp = wp.lock()) {
        std::cout << "wp value: " << *tmp << "\n";
    }
}

总结

智能指针是现代 C++ 的重要工具,合理使用可以大幅提升代码安全性和可维护性。

unique_ptr:独占所有权

shared_ptr:共享所有权

weak_ptr:弱引用,避免循环引用

相关推荐
GIS阵地43 分钟前
QgsSingleBandPseudoColorRenderer 完整详解(QGIS 3.40.13 C++)
开发语言·前端·c++·qt·qgis
王维同学1 小时前
[原创][Windows C++]LSA 认证、安全与通知包的注册表枚举
c++·windows·安全
_wyt0012 小时前
完全背包问题详解
c++·背包dp
皓月斯语4 小时前
B3842 [GESP202306 三级] 春游 题解
数据结构·c++·算法·题解
CedarQR5 小时前
万字长文:从零在 RK3588 上部署 PaddleSpeech 中文 TTS 全流程(FastSpeech2 + HiFiGAN)
开发语言·c++·嵌入式硬件·ubuntu·json
萌动的小火苗5 小时前
嵌入式开发中的栈与队列:任务调度为什么依赖数据结构
数据结构·c++·单片机·嵌入式硬件
星恒随风5 小时前
C++ STL 栈详解:stack 的使用、经典题目与简单模拟实现
开发语言·数据结构·c++·笔记·学习
txzrxz5 小时前
单调队列讲解
数据结构·c++·算法·单调队列
WWTYYDS_6666 小时前
JsonCpp超详细使用教程
c++
Joey_friends6 小时前
指纹authenticate流程图
android·java·c++