How does the pimpl idiom reduce dependencies?

前端 未结 7 2049
我在风中等你
我在风中等你 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

    The main advantage is that the clients of the interface aren't forced to include the headers for all your class's internal dependencies. So any changes to those headers don't cascade into a recompile of most of your project. Plus general idealism about implementation-hiding.

    Also, you wouldn't necessarily put your impl class in its own header. Just make it a struct inside the single cpp and make your outer class reference its data members directly.

    Edit: Example

    SomeClass.h

    struct SomeClassImpl;
    
    class SomeClass {
        SomeClassImpl * pImpl;
    public:
        SomeClass();
        ~SomeClass();
        int DoSomething();
    };
    

    SomeClass.cpp

    #include "SomeClass.h"
    #include "OtherClass.h"
    #include 
    
    struct SomeClassImpl {
        int foo;
        std::vector otherClassVec;   //users of SomeClass don't need to know anything about OtherClass, or include its header.
    };
    
    SomeClass::SomeClass() { pImpl = new SomeClassImpl; }
    SomeClass::~SomeClass() { delete pImpl; }
    
    int SomeClass::DoSomething() {
        pImpl->otherClassVec.push_back(0);
        return pImpl->otherClassVec.size();
    }
    

提交回复
热议问题