PIMPL More Stable APIs

Pimpl a.k.a (Pointer to implentation) 是一种现代C++技术,用于隐藏实现,尽量减少耦合,并分离接口。

为什么使用pimpl?

在软件开发中,使用Pimpl有一下三点好处

  • 最小化编译依赖
  • 实现接口和实现的分离
  • 可移植性

Pimpl头文件

#ifndef IMPL_PERSON_H
#define IMPL_PERSON_H
#include <string>
#include <memory>

class Person {
public:
  Person(std::string name);
  ~Person();
  std::string GetAttributes();

private:
  struct pImplPerson;
  std::unique_ptr<pImplPerson> m_impl;
};

#endif // IMPL_PERSON_H

Pimpl实现

#include "person.h"
#include <iostream>

struct Person::pImplPerson {
  std::string m_name;
  std::string m_strength;
  std::string m_speed;
};

Person::Person(std::string name) {
  m_impl = std::make_unique<pImplPerson>();
  m_impl->m_name = name;
  m_impl->m_speed = "n/a";
  m_impl->m_strength = "n/a";
}

Person::~Person() {}

std::string Person::GetAttributes() {
  std::string retStr = "name: " + m_impl->m_name +
                       " speed: " + m_impl->m_speed +
                       " strength: " + m_impl->m_strength;
  return retStr;
}

参考链接

Lofi&Cafe

Blog about tech and life!


2022-07-09