Exceptional C++

【Exceptional C++(16)】Fast Pimpl技

2018-01-30  本文已影响23人  downdemo
// file y.h
#include "x.h"
class Y {
    ...
    X x_;
};
// file y.cpp
Y::Y() {}
// file y.h
class X;
class Y {
    ...
    X* px_;
};
// file y.cpp
#include "x.h"
Y::Y() : px_(new X) {}
Y::~Y() { delete px_; px_ = 0; }
// file y.h
class YImpl;
class Y {
    ...
    YImpl* pimpl_;
};
// file y.cpp
#include "x.h"
struct YImpl {
    ... // private stuff here
    void* operator new(size_t) { ... }
    void operator delete(void*) { ... }
};
Y::Y() : pimpl_(new YImpl) {}
Y::~Y() { delete pimpl_; pimpl_ = 0; }
template<size_t S>
class FixedAllocator {
public:
    void* Allocate(...);
    void Deallocate(void*);
private:
    // implemented using static?
};
class FixedAllocator {
public:
    static FixedAllocator* Instance();
    void* Allocate(size_t);
    void Deallocate(void*);
private:
    // singleton implementation
};
// 用一个辅助基类封装调用
struct FastPimpl {
    void* operator new(size_t s) {
        return FixedAllocator::Instance()->Allocate(s);
    }
    void operator delete(void* p) {
        FixedAllocator::Instance()->Deallocate(p);
    }
};
// 现在可以很容易地写出任意的Fast Pimpl
struct YImpl : FastPimpl {
    ... // private stuff here
};
上一篇下一篇

猜你喜欢

热点阅读