PIMPL idiom的核心是将类的实现细节移至独立的私有类中,主类通过指针(如std::unique_ptr)访问,从而隐藏实现、减少编译依赖、提升封装性和二进制兼容性。

PIMPL(Pointer to IMPLementation)是一种常见的C++设计模式,用于隐藏类的实现细节,降低编译依赖,提升代码的封装性和二进制兼容性。它通过将具体实现移到一个独立的、不公开的类中,并在主类中使用指向该实现类的指针来实现。
PIMPL idiom 的核心思想是:把类的数据成员从头文件中移出,放到一个只有源文件可见的私有类或结构体中。主类只保留一个指向这个私有实现的指针,通常使用 std::unique_ptr 管理生命周期。
这样做的直接好处是:当实现发生变化时,只要接口不变,就不需要重新编译包含该头文件的其他代码,有效减少了编译时间的传播。
以一个简单的示例说明 PIMPL 的典型写法:
立即学习“C++免费学习笔记(深入)”;
widget.h
#pragma once
#include <memory>
<p>class Widget {
public:
Widget();
~Widget();
Widget(const Widget&);
Widget& operator=(const Widget&);</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">void do_something();private: class Impl; // 前向声明 std::uniqueptr<Impl> pimpl; // 指向实现的指针 };
widget.cpp
#include "widget.h"
#include <string>
#include <vector>
<p>class Widget::Impl {
public:
void do_something() { /<em> 具体实现 </em>/ }</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">std::string name;
std::vector<int> data;
// 可以随意添加成员而不影响头文件};
Widget::Widget() : pimpl_(std::make_unique<Impl>()) {} Widget::~Widget() = default; // 必须在cpp中定义,因为 unique_ptr 需要知道 Impl 的完整类型
Widget::Widget(const Widget& other) : pimpl_(std::makeunique<Impl>(*other.pimpl)) {}
Widget& Widget::operator=(const Widget& other) { pimpl_ = other.pimpl_; return *this; }
void Widget::dosomething() { pimpl->do_something(); }
PIMPL 模式在大型项目中特别有价值,主要原因包括:
虽然PIMPL有很多优点,但也带来一些开销和限制:
基本上就这些。PIMPL 是一种权衡——用一点运行时成本换取更好的模块化和维护性。在接口稳定、实现多变的类中,它是非常值得推荐的设计选择。
以上就是c++++中的PIMPL idiom是什么_隐藏实现细节的PIMPL设计模式详解的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号