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

相关推荐
郝学胜_神的一滴14 小时前
CMake 034:生成器表达式:解耦构建时序、精简分支逻辑的终极利器
c++·cmake
见过夏天1 天前
C++ 基础入门完全指南
c++
用户805533698033 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
BadBadBad__AK3 天前
线段树维护区间 k 次方和
c++·数学·算法·stl
卷无止境4 天前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境4 天前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴5 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境7 天前
C++ 的Eigen 库全解析
c++
卷无止境7 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴7 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake