想象一下。
我想创建不暴露任何底层实现的类。甚至没有指向实现的指针。
我会用一个全局对象池来做到这一点。
像这样。
在类 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/