PImpl 并不能使我免于导出 STL

PImpl Doesn't Save Me from having to Export STL

本文关键字:于导出 STL 并不能 PImpl      更新时间:2023-10-16

我采用了PImpl设计,以避免从动态库中导出STL。

旧:

//In header file
class Foo{
public:
    const map<char, char>& getMap() {return _map;}
private:
    map<char, char> _map;
};

新增:

//In header file
class Foo{
public:
    Foo();
    ~Foo();
   const map<char, char>& getMap();
private:
    struct Impl;
    Impl* _pimpl;
};
//In implementation file
struct Foo::Impl{
    map<char, char> _map;
}
Foo::Foo(): _pimpl(new Impl){}
Foo::~Foo(){delete _pimpl;}
const map<char, char>& Foo::getMap(){return _pimpl->_map;}

然而,明显的问题是,我仍然必须将map作为库的一部分导出。我不想停止返回STL,但我看不到绕过它的方法。有没有另一种范式仍然可以让我返回STL,而不必导出它?

解决方案是不在类的接口中使用std::map,而是实现所需的方法子集。例如,假设您希望通过operator[]、访问读写元素

// Foo.h
class Foo{
public:
    Foo();
    ~Foo();
   const char& operator[](char key) const;
   char& operator[](char key);
private:
    struct Impl;
    Impl* _pimpl;
};

然后

// Foo.cpp
#include <map>
struct Foo::Impl
{
    std::map<char, char> _map;
};
Foo::Foo() : _pimpl(new Impl){}
Foo::~Foo(){delete _pimpl;} // don't forget to take care of copy and assignment
const char& Foo::operator[](char key) const {return _pimpl->_map[key];}
char& Foo::operator[](char key) {return _pimpl->_map[key];}