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

相关推荐
倒头就睡的小比特1 天前
算法竞赛C++常用的STL
c++·算法
weilx12341 天前
C++笔记-文件IO-<fcntl.h>
c++
Smileyqp沛沛1 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
C语言小火车1 天前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光1 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
吞下星星的少年·-·1 天前
C++ 萌新语法入门篇
c++·算法比赛
霍霍的袁1 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
another heaven1 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法
程序猿编码1 天前
告别改源码适配模型:纯 C++ 可配置 LLM 推理引擎,全格式全结构兼容
c++·大模型·llm·推理引擎
此生决int1 天前
深入理解C++系列(20)——C++11(下)
开发语言·c++