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:弱引用,避免循环引用

相关推荐
j_xxx404_8 分钟前
Linux:静态链接与动态链接深度解析
linux·运维·服务器·c++·人工智能
c++之路1 小时前
C++23概述
java·c++·c++23
学涯乐码堂主3 小时前
有趣的“打擂台算法”
c++·算法·青少年编程·gesp
云栖梦泽3 小时前
Linux内核与驱动:14.SPI子系统
linux·运维·服务器·c++
Gary Studio4 小时前
安卓HAL C++基础-智能指针
开发语言·c++
还是阿落呀4 小时前
基本控制结构2
c++
多思考少编码4 小时前
PAT甲级真题1001 - 1005题详细题解(C++)(个人题解)
c++·python·最短路·pat·算法竞赛
极客智造5 小时前
C++ 标准 IO 流全详解:cin /cout/get /getline 原理、用法、区别与避坑
c++·io
charlie1145141915 小时前
嵌入式C++工程实践第20篇:GPIO 输入模式内部电路 —— 芯片是如何“听“到外部信号的
开发语言·c++·stm32·单片机
样例过了就是过了8 小时前
LeetCode热题100 分割等和子集
数据结构·c++·算法·leetcode·动态规划