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
英文地址,請注明出處:http://en.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”視圖包括邏輯視圖、實現視圖、進程視圖、部署視…