PIMPL的优点和注意事项

优点

  • 降低耦合度:使用PIMPL可以减少头文件的依赖,降低编译时的耦合度。
  • 隐藏实现细节:实现细节对使用者是不可见的,有利于封装。
  • 编译依赖减少:当实现改变时,不需要重新编译依赖于接口的代码,只需重新编译实现代码即可。

注意事项:

  • 运行时性能:每次通过指针访问实现类可能会有轻微的性能开销。
  • 资源管理:需要在构造函数中分配内存,在析构函数中释放内存。可以考虑使用智能指针(如 std::unique_ptr)简化资源管理。
  • 通过使用PIMPL技术,你可以有效地将你的类的接口与实现分离,同时避免了不必要的头文件包含,从而减少编译依赖和编译时间。

使用 PIMPL(Pointer to Implementation)技术可以有效地隐藏类的实现细节,减少编译依赖,同时使得接口(头文件)与实现(源文件)之间的耦合度降低。这样,当实现改变时,不会强制重新编译依赖于该头文件的其他代码,只要接口保持不变。

header file

// use.h
#pragma once

// 前向声明


class Use{
public:
    Use();
    ~Use(); // 注意:需要一个析构函数的声明

    // 禁用复制构造函数和赋值操作符
    Use(const Use&) = delete;
    Use& operator=(const Use&) = delete;

private:
    // PIMPL Idiom 的实现部分
    class Impl;
   std::unique_ptr<Impl> pImpl; // 唯一指向实现部分的指针
};

source file

// Use.cpp
#include<memory>
#include "Use.h"
#include "other.h"

class Use::Impl : public name::CallBack {
    // 实现细节
};

Use::Use() : pImpl(std::make_unique<Impl>()) {
    // 构造函数实现
}

Use::~Use() {
   
}

// 其他成员函数的实现...

posted @ 2024-03-01 18:04  simp00  阅读(15)  评论(0编辑  收藏  举报