C++智能指针编程实例

智能指针是C++11引入的重要特性,用于自动管理动态分配的内存,防止内存泄漏。下面介绍几种高级智能指针编程实例。

1. 共享所有权模式 (shared_ptr)

循环引用问题及解决方案

#include <memory>
#include <iostream>class B; // 前向声明class A {
public:std::shared_ptr<B> b_ptr;~A() { std::cout << "A destroyed\n"; }
};class B {
public:std::shared_ptr<A> a_ptr; // 这里会导致循环引用~B() { std::cout << "B destroyed\n"; }
};void circularReferenceProblem() {auto a = std::make_shared<A>();auto b = std::make_shared<B>();a->b_ptr = b;b->a_ptr = a; // 循环引用// 离开作用域时,a和b不会被销毁
}// 使用weak_ptr解决循环引用
class B_fixed;class A_fixed {
public:std::shared_ptr<B_fixed> b_ptr;~A_fixed() { std::cout << "A_fixed destroyed\n"; }
};class B_fixed {
public:std::weak_ptr<A_fixed> a_ptr; // 使用weak_ptr打破循环~B_fixed() { std::cout << "B_fixed destroyed\n"; }
};void circularReferenceSolution() {auto a = std::make_shared<A_fixed>();auto b = std::make_shared<B_fixed>();a->b_ptr = b;b->a_ptr = a; // weak_ptr不会增加引用计数// 离开作用域时,a和b会被正确销毁
}

2. 独占所有权模式 (unique_ptr)

工厂模式应用

#include <memory>
#include <iostream>class Base {
public:virtual void doSomething() = 0;virtual ~Base() = default;
};class Derived1 : public Base {
public:void doSomething() override {std::cout << "Derived1 doing something\n";}
};class Derived2 : public Base {
public:void doSomething() override {std::cout << "Derived2 doing something\n";}
};enum class ProductType { TYPE1, TYPE2 };std::unique_ptr<Base> createProduct(ProductType type) {switch(type) {case ProductType::TYPE1: return std::make_unique<Derived1>();case ProductType::TYPE2: return std::make_unique<Derived2>();default: return nullptr;}
}void factoryPatternExample() {auto product1 = createProduct(ProductType::TYPE1);auto product2 = createProduct(ProductType::TYPE2);product1->doSomething();product2->doSomething();// unique_ptr会自动管理内存
}

3. 弱引用模式 (weak_ptr)

缓存系统实现

#include <memory>
#include <unordered_map>
#include <iostream>class ExpensiveResource {
public:ExpensiveResource(int id) : id(id) {std::cout << "Creating resource " << id << "\n";}~ExpensiveResource() {std::cout << "Destroying resource " << id << "\n";}void use() {std::cout << "Using resource " << id << "\n";}
private:int id;
};class ResourceCache {
public:std::shared_ptr<ExpensiveResource> getResource(int id) {std::shared_ptr<ExpensiveResource> res;auto it = cache.find(id);if (it != cache.end()) {res = it->second.lock(); // 尝试从weak_ptr获取shared_ptr}if (!res) {res = std::make_shared<ExpensiveResource>(id);cache[id] = res; // 存储weak_ptr}return res;}size_t size() const { return cache.size(); }private:std::unordered_map<int, std::weak_ptr<ExpensiveResource>> cache;
};void cacheExample() {ResourceCache cache;{auto res1 = cache.getResource(1);auto res2 = cache.getResource(2);res1->use();res2->use();std::cout << "Cache size: " << cache.size() << "\n";}// 资源已释放,但缓存中仍有weak_ptrstd::cout << "Cache size after resources out of scope: " << cache.size() << "\n";// 再次获取资源1,会创建新实例auto res1_again = cache.getResource(1);res1_again->use();
}

4. 自定义删除器

文件指针管理

#include <memory>
#include <cstdio>void fileDeleter(FILE* file) {if (file) {std::fclose(file);std::cout << "File closed\n";}
}
void customDeleterExample() {// 使用自定义删除器管理文件指针std::unique_ptr<FILE, decltype(&fileDeleter)> filePtr(std::fopen("example.txt", "w"), &fileDeleter);if (filePtr) {std::fputs("Hello, world!", filePtr.get());}// 离开作用域时自动调用fileDeleter关闭文件
}

5. 多态与智能指针

多态对象管理

#include <memory>
#include <vector>
#include <iostream>class Animal {
public:virtual void speak() const = 0;virtual ~Animal() = default;
};class Dog : public Animal {
public:void speak() const override {std::cout << "Woof!\n";}
};class Cat : public Animal {
public:void speak() const override {std::cout << "Meow!\n";}
};void polymorphismExample() {std::vector<std::unique_ptr<Animal>> animals;animals.push_back(std::make_unique<Dog>());animals.push_back(std::make_unique<Cat>());for (const auto& animal : animals) {animal->speak();}// unique_ptr会自动调用正确的析构函数
}

6. 共享指针与弱指针结合

观察者模式实现

#include <memory>
#include <vector>
#include <iostream>
#include <algorithm>class Observer;class Subject {
public:void attach(std::weak_ptr<Observer> observer) {observers.push_back(observer);}void notifyAll();private:std::vector<std::weak_ptr<Observer>> observers;
};class Observer : public std::enable_shared_from_this<Observer> {
public:Observer(std::shared_ptr<Subject> subject) : subject(subject) {subject->attach(weak_from_this());}virtual void update() = 0;virtual ~Observer() = default;protected:std::shared_ptr<Subject> subject;
};void Subject::notifyAll() {for (auto it = observers.begin(); it != observers.end(); ) {if (auto observer = it->lock()) {observer->update();++it;} else {it = observers.erase(it);}}
}class ConcreteObserver : public Observer {
public:using Observer::Observer;void update() override {std::cout << "Observer notified!\n";}
};void observerPatternExample() {auto subject = std::make_shared<Subject>();auto observer1 = std::make_shared<ConcreteObserver>(subject);auto observer2 = std::make_shared<ConcreteObserver>(subject);subject->notifyAll();// 当observer超出作用域时,weak_ptr会自动失效
}

7. 智能指针与多线程

线程安全共享数据

#include <memory>
#include <thread>
#include <vector>
#include <mutex>
#include <iostream>class ThreadSafeData {
public:void add(int value) {std::lock_guard<std::mutex> lock(mutex);data.push_back(value);}void print() const {std::lock_guard<std::mutex> lock(mutex);for (int val : data) {std::cout << val << " ";}std::cout << "\n";}private:mutable std::mutex mutex;std::vector<int> data;
};void worker(std::shared_ptr<ThreadSafeData> data, int id) {for (int i = 0; i < 5; ++i) {data->add(id * 100 + i);}
}void threadSafeExample() {auto data = std::make_shared<ThreadSafeData>();std::vector<std::thread> threads;for (int i = 0; i < 3; ++i) {threads.emplace_back(worker, data, i + 1);}for (auto& t : threads) {t.join();}data->print();
}

8. 智能指针与STL容器

容器中存储智能指针

#include <memory>
#include <vector>
#include <iostream>class Item {
public:Item(int id) : id(id) {std::cout << "Item " << id << " created\n";}~Item() {std::cout << "Item " << id << " destroyed\n";}void use() {std::cout << "Using item " << id << "\n";}
private:int id;
};void stlContainerExample() {std::vector<std::shared_ptr<Item>> items;items.push_back(std::make_shared<Item>(1));items.push_back(std::make_shared<Item>(2));items.push_back(std::make_shared<Item>(3));// 复制智能指针会增加引用计数auto item2 = items[1];for (const auto& item : items) {item->use();}// 当items和item2超出作用域时,Item对象会被正确销毁
}

这些实例展示了C++智能指针在各种场景下的高级应用,包括内存管理、设计模式实现、多线程编程等。合理使用智能指针可以显著提高代码的安全性和可维护性。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/diannao/87995.shtml
繁体地址,请注明出处:http://hk.pswp.cn/diannao/87995.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

单元测试总结

一、测试方案: 单元测试方案应包括以下步骤: 1.理解代码结构:仔细阅读代码,理解程序的结构、逻辑和算法。 2.制定测试目标:明确你想要测试的功能和输出结果; 3.撰写测试用例:编写涵盖所有测试目标的测试用例; 4.执行测试:运行测试用例以验证功能的正确性; 5.编写报告:根据测试…

Spring面向切面编程AOP(2)

前置通知&#xff08;Before Advice&#xff09; 前置通知在目标方法执行之前被调用&#xff0c;常用于执行一些预处理逻辑&#xff0c;例如权限验证、参数校验等。在 Spring 配置文件中&#xff0c;前置通知通过<aop:before>标签进行配置&#xff0c;以下是一个典型的示…

设备故障预测与健康管理技术:从数据到决策的工业智能进化之路​

在工业 4.0 与智能制造浪潮的推动下&#xff0c;设备故障预测与健康管理&#xff08;Prognostics and Health Management, PHM&#xff09;技术已成为企业实现数字化转型的核心驱动力。据统计&#xff0c;制造业中设备非计划停机 1 小时的平均损失高达 25 万美元&#xff0c;而…

RabbitMQ从入门到实践:消息队列核心原理与典型应用场景

在现代应用开发中&#xff0c;系统各部分之间的通信至关重要。这就是像RabbitMQ这样的消息代理发挥作用的地方。无论您是在构建微服务架构、实现任务队列&#xff0c;还是开发实时聊天应用程序&#xff0c;RabbitMQ都可能成为改变游戏规则的工具。本文将深入探讨RabbitMQ是什么…

基于Spring Boot和Vue的网上军事论坛设计与实现

目录 一.&#x1f981;前言二.&#x1f981;开源代码与组件使用情况说明三.&#x1f981;核心功能1. ✅算法设计2. ✅Java开发语言3. ✅Redis数据库4. ✅部署项目 四.&#x1f981;演示效果1. 管理员模块1.1 用户管理1.2 内容审核1.3 权限分配1.4 菜单管理1.5 字典管理 2. 用户…

LLMs基础学习(八)强化学习专题(6)

LLMs基础学习&#xff08;八&#xff09;强化学习专题&#xff08;6&#xff09; 文章目录 LLMs基础学习&#xff08;八&#xff09;强化学习专题&#xff08;6&#xff09;深度强化学习&#xff08;DQN&#xff09;DQN 起源&#xff1a;《Playing Atari with Deep Reinforceme…

JVM(10)——详解Parallel垃圾回收器

Parallel 垃圾回收器&#xff08;也称为 吞吐量优先收集器&#xff09;。它是 Java 早期&#xff08;特别是 JDK 8 及之前&#xff09;在多核处理器上的默认垃圾回收器&#xff0c;其核心设计目标是最大化应用程序的吞吐量。 一、Parallel 回收器的定位与设计目标 核心目标&am…

MySQL(91)什么是分布式数据库?

分布式数据库是一种将数据存储在多个物理位置的数据库系统。这些位置可能分布在不同的服务器、数据中心甚至地理位置。分布式数据库系统允许数据的存储、处理和访问分布在多个节点上&#xff0c;以提高数据的可用性、可靠性、可扩展性和性能。 1. 分布式数据库的特点 1.1 数据…

Java事务失效(面试题)的常见场景

1. 方法非public修饰 原理&#xff1a; Spring AOP代理&#xff08;CGLIB或JDK动态代理&#xff09;默认无法拦截非public方法。 示例&#xff1a; Service public class UserService {Transactionalvoid updateUser() { // 非public方法// 事务不会生效&#xff01;} } 修…

GitHub 趋势日报 (2025年06月20日)

&#x1f4ca; 由 TrendForge 系统生成* | &#x1f310; https://trendforge.devlive.org/ &#x1f310; 本日报中的项目描述已自动翻译为中文 &#x1f4c8; 今日获星趋势图 今日获星趋势图 1810 data-engineer-handbook 373 n8n 295 anthropic-cookbook 291 automatisch…

qt常用控件--01

文章目录 qt常用控件--01上一篇文章的补充windowTitle属性windowIcon属性windowOpaCity属性cursor属性font属性结语 很高兴和大家见面&#xff0c;给生活加点impetus&#xff01;&#xff01;开启今天的编程之路&#xff01;&#xff01; 今天我们进一步c11中常见的新增表达 作…

C++ 中 string 类的解析及简易自我实现

目录 引言 标准库中的 string 类 功能概述 常见操作示例 自我实现简易 string 类 代码结构概述 1. String11.h 头文件 类的成员变量 迭代器相关 构造函数和析构函数 基本访问和修改方法 赋值运算符重载 内存管理和扩容 以下代码在.cpp文件中解析: 2. String11.…

计算机的性能指标(选择题0~1题无大题)

存储器的性能指标 总容量存储单元个数*存储字长 bit 例&#xff1a;MAR16位&#xff0c;MDR16位 总容量2的16次方*16bit 补充&#xff1a; n个二进制位就有2的n次方不同的状态 一般描述文件大小容量单位 2的10次方&#xff1a;K 2的20次方&#xff1a;M 2的…

React 核心原理与Fiber架构

目录 一、虚拟 DOM 二、Diffing 算法 三、Fiber 架构 四、渲染流程 1. Render 阶段&#xff08;可中断异步过程&#xff09; 2. Commit 阶段&#xff08;同步不可中断&#xff09; 五、时间切片&#xff08;Time Slicing&#xff09; 六、核心流程步骤总结 1. 状态更新…

【破局痛点,赋能未来】领码 SPARK:铸就企业业务永续进化的智慧引擎—— 深度剖析持续演进之道,引领数字化新范式

摘要 在瞬息万变的数字时代&#xff0c;企业对业务连续性、敏捷创新及高效运营的需求日益迫切。领码 SPARK 融合平台&#xff0c;秉持“持续演进”这一核心理念&#xff0c;以 iPaaS 与 aPaaS 为双擎驱动&#xff0c;深度融合元数据驱动、智能端口调度、自动化灰度切换、AI 智…

掌握C++核心特性

目标&#xff1a; 掌握C核心特性&#xff0c;为嵌入式开发打基础 好的&#xff0c;我来为你详细梳理一下 继承与多态、虚函数 相关的知识点&#xff0c;包括单继承、多继承、虚函数表机制、纯虚函数与抽象类、动态绑定。以下内容适合中等难度层次的理解&#xff0c;便于考试复…

python的高校教师资源管理系统

目录 技术栈介绍具体实现截图系统设计研究方法&#xff1a;设计步骤设计流程核心代码部分展示研究方法详细视频演示试验方案论文大纲源码获取/详细视频演示 技术栈介绍 Django-SpringBoot-php-Node.js-flask 本课题的研究方法和研究步骤基本合理&#xff0c;难度适中&#xf…

Java Collections工具类:高效集合操作

Collections工具类概述 Collections是Java提供的集合操作工具类&#xff0c;位于java.util包中&#xff0c;包含大量静态方法&#xff0c;用于对List、Set、Map等集合进行排序、查找、替换、同步化等操作。 常用方法及代码示例 排序操作 sort(List<T> list)&#xff1a…

vue指令总结

vue指令总结 一、总述 二、代码实现&#xff08;内含大量注释&#xff09; <!DOCTYPE html> <html> <head><meta charset"utf-8"><title>vue入门</title><!-- 使用Vue 3官方CDN --><script src"https://unpkg.c…

RUP——统一软件开发过程

RUP概述 RUP&#xff08;Rational Unified Process&#xff09;&#xff0c;统一软件开发过程&#xff0c;统一软件过程是一个面向对象且基于网络的程序开发方法论。 在RUP中采用“41”视图模型来描述软件系统的体系结构。“41”视图包括逻辑视图、实现视图、进程视图、部署视…