文章

pimpl 编程技巧

pimpl 编程技巧

Pimpl(Pointer to Implementation)是一种 C++ 编程技巧,用于实现数据封装和减少编译依赖。它的基本思想是将类的实现细节放在一个单独的类中,并通过指针在主类中引用这个实现类。Pimpl 模式通常在库开发中使用,以便提供稳定的 API,同时允许内部实现的灵活性。

示例

demo.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#ifndef __DEMO_H__
#define __DEMO_H__

#include <memory>

class Demo {
public:
    Demo(int a, int b);
    ~Demo();
    int add();

private:
    class Impl;
    std::unique_ptr<Impl> m_pimpl;
};

#endif // __DEMO_H__

demo.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "demo.h"

class Demo::Impl {
private:
    int m_x;
    int m_y;

public:
    Impl(int a, int b)
        : m_x(a)
        , m_y(b)c{}
    int add() {
        return m_x + m_y;
    }
};

Demo::Demo(int a, int b)
    : m_pimpl(std::make_unique<Impl>(a, b)){}
Demo::~Demo(){}

int Demo::add() {
    return m_pimpl->add();
}

优点

  1. 减少编译时间:当实现细节发生变化时,只需重新编译实现类,而不需要重新编译使用该类的所有代码。
  2. 隐藏实现细节:用户只需了解接口,而不需要关心具体的实现,这有助于提升代码的封装性和可维护性。
  3. 降低类的大小:主类的大小会变得更小,因为它只包含指向实现的指针,而不是所有的成员变量。
本文由作者按照 CC BY 4.0 进行授权