How does the pimpl idiom reduce dependencies?

前端 未结 7 2046
我在风中等你
我在风中等你 2020-12-10 05:35

Consider the following:

PImpl.hpp

class Impl;

class PImpl
{
    Impl* pimpl;
    PImpl() : pimpl(new Impl) { }
    ~PImpl() { delete pimpl; }
    vo         


        
7条回答
  •  执念已碎
    2020-12-10 06:30

    Not all classes benefit from p-impl. Your example has only primitive types in its internal state which explains why there's no obvious benefit.

    If any of the members had complex types declared in another header, you can see that p-impl moves the inclusion of that header from your class's public header to the implementation file, since you form a raw pointer to an incomplete type (but not an embedded field nor a smart pointer). You could just use raw pointers to all your member variables individually, but using a single pointer to all the state makes memory management easier and improves data locality (well, there's not much locality if all those types use p-impl in turn).

提交回复
热议问题