PImpl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef PIMPL_H
#define PIMPL_H
#include <memory>

class pImpl {
struct Impl;
std::unique_ptr<Impl> impl;
public:
pImpl();
~pImpl();
void dosomething();
};

#endif // PIMPL_H
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "pImpl.h"

#include <iostream>

struct pImpl::Impl {
int a,b,c,d;
void dosomething() {
std::cout << "dosomething1" << std::endl;
}
};
//必须将所有都实现在.cpp中,因为在.h中Impl是一个不完整类型
pImpl::pImpl() : impl(new Impl) {}
pImpl::~pImpl() = default;
void pImpl::dosomething() {
impl->dosomething();
}
1
2
3
4
5
#include"pImpl.h"
int main() {
pImpl p;
p.dosomething();
}

更改这个Impl类的时候就不用再重新构建一遍main,因为pImpl.h完全没变


PImpl
https://lhish.github.io/project/hide/PImpl/
作者
lhy
发布于
2025年8月16日
许可协议