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

相关推荐
blasit3 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_1 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星1 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
端平入洛4 天前
auto有时不auto
c++
哇哈哈20215 天前
信号量和信号
linux·c++
多恩Stone5 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马5 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝5 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc5 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法