当前位置: 首页 > news >正文

C++ 中的 Pimpl 惯用法

C++ 中的 Pimpl 惯用法

介绍

Pimpl(Pointer to Implementation)是一种常见的 C++ 设计模式,用于隐藏类的实现细节,从而减少编译依赖和提高编译速度。本文将通过一个较为复杂的例子,展示如何使用智能指针(如 std::unique_ptr)来实现 Pimpl 惯用法。

什么是 Pimpl 惯用法?

Pimpl 是 “Pointer to Implementation” 的缩写,这个模式可以帮助我们:

  • 将接口和实现分离
  • 减少头文件中的依赖
  • 加速编译

基本实现

基本的 Pimpl 实现需要一个前置声明的内部类和一个指向该内部类的指针。在这里,我们使用 std::unique_ptr 来管理这个内部类的实例。

MyClass.h

#include <memory>class MyClassImpl; // 前置声明class MyClass {
public:MyClass();~MyClass();void DoSomething();private:std::unique_ptr<MyClassImpl> pimpl;
};

MyClass.cpp

#include "MyClass.h"class MyClassImpl {
public:void DoSomething() {// 实现细节}
};MyClass::MyClass() : pimpl(std::make_unique<MyClassImpl>()) {}
MyClass::~MyClass() = default;void MyClass::DoSomething() {pimpl->DoSomething();
}

示例

假设我们有一个 Car 类,它有多个组件,如 EngineWheel

Car.h

#include <memory>
class CarImpl;class Car {
public:Car();~Car();void Start();void Stop();private:std::unique_ptr<CarImpl> pimpl;
};

Car.cpp

#include "Car.h"
#include "Engine.h"
#include "Wheel.h"class CarImpl {
public:Engine engine;Wheel wheel[4];void Start() {engine.Start();// 其他逻辑}void Stop() {engine.Stop();// 其他逻辑}
};Car::Car() : pimpl(std::make_unique<CarImpl>()) {}
Car::~Car() = default;void Car::Start() {pimpl->Start();
}void Car::Stop() {pimpl->Stop();
}

在这个例子中,Car 的用户只需要包含 Car.h,而不需要知道 EngineWheel 的存在。这样就降低了编译依赖并提高了编译速度。

总结

通过使用 Pimpl 惯用法和智能指针,我们能更有效地隐藏实现细节,提高编译速度,并使代码更易于维护。

http://www.lryc.cn/news/152901.html

相关文章:

  • 【个人博客系统网站】统一处理 · 拦截器
  • 深入探索PHP编程:文件操作与输入/输出(I/O)
  • 基于jeecg-boot的flowable流程自定义业务驳回到发起人的一种处理方式
  • 【大数据知识】大数据平台和数据中台的定义、区别以及联系
  • 华为OD:IPv4地址转换成整数
  • 2023.9 - java - 浅拷贝
  • STM32f103入门(10)ADC模数转换器
  • 实训笔记8.28
  • 机器学习笔记之最优化理论与方法(五)凸优化问题(上)
  • 在Windows10上编译grpc工程,得到protoc.exe和grpc_cpp_plugin.exe
  • 一些测试知识
  • Socket交互的基本流程?
  • css 分割线中间带文字
  • 会不会激发对modern c++的新兴趣
  • Nginx服务器如何配合Java开发项目
  • 【LeetCode-中等题】994. 腐烂的橘子
  • K8s部署单机mysql
  • Midjourney学习(二)参数的基础
  • Ubuntu安装Protobuf,指定版本
  • 没有使用sniffer dongle在windows抓包蓝牙方法分享
  • 解决Debian系统通过cifs挂载smb后,中文目录乱码问题
  • springboot整合jquery实现前后端数据交互
  • TypeScript 中的类型检查实用函数
  • JavaScript中的事件委托(event delegation)
  • ubuntu OCR 脚本
  • Go死码消除
  • 基于改进莱维飞行和混沌映射的粒子群优化BP神经网络分类研究(Matlab代码实现)
  • 12. 自动化项目实战
  • Window11下载安装jdk8-jdk11与环境变量的配置
  • Vector Search with OpenAI Embeddings: Lucene Is All You Need