c++ - 使用 Pimpl 的高级变体时可能会影响性能?

标签 c++ pimpl-idiom

想象一下。

我想创建不暴露任何底层实现的类。甚至没有指向实现的指针。

我会用一个全局对象池来做到这一点。

像这样。

在类 TestImpl 中实现的类 Test。

当构造 Test 时,它会在全局对象池中为自己创建一个 TestImpl。

对象池基本上是每种类型的映射。键是测试实例的内存地址,值是相应的 TestImpl。所以每次调用Test上的成员函数时,都会先从对象池中获取对应的TestImpl,以this指针为key。

这种对象池当然要同步,需要锁。

您认为这样的解决方案会对性能造成多大影响?

最佳答案

ifc.h

struct ifc {
    virtual ~ifc() {}
    virtual void api() = 0;

    static ifc* create();
};

实现.cc

#include "ifc.h"

struct impl: ifc {
    virtual void api() override;
}

void impl::api() {
    // code here
}

ifc* ifc::create() {
    // or use shared pointer / untrusive pointer and return object back to a pool
    // if dynamic memory allocation is not desired (but rather just keep it simple  
    // and plug something like TCMalloc first (which does low level pooling)
    // and see if it gets better)
    return new impl();
}

关于c++ - 使用 Pimpl 的高级变体时可能会影响性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26139032/

相关文章:

c++ - 退回 VLA 安全吗?

c++ - 如何将 Combobox 插入到 Tablewidget

c++ - 是否有人建议扩展 C++ 语言以消除 pimpl?

c++ - 带有继承的 Pimpl 成语

c++11 - 使用 unique_ptr 的 pimpl 惯用语中的 ABI

c++ - 在派生类中使用 std::unique_ptr 的 Pimpl

c++ - 错误 : invalid conversion from 'void (*)()' to 'void (*)()' -- what?

c++ - 使用级联相关神经网络(再训练)

c++ - Qt Designer 类似于 3D Slicer 的菜单格式

c++ - 在 C++ 中隐藏实现细节