Is the pImpl idiom really used in practice?

后端 未结 11 1454
渐次进展
渐次进展 2020-11-22 17:21

I am reading the book \"Exceptional C++\" by Herb Sutter, and in that book I have learned about the pImpl idiom. Basically, the idea is to create a structure for the p

11条回答
  •  醉酒成梦
    2020-11-22 17:38

    I used to use this technique a lot in the past but then found myself moving away from it.

    Of course it is a good idea to hide the implementation detail away from the users of your class. However you can also do that by getting users of the class to use an abstract interface and for the implementation detail to be the concrete class.

    The advantages of pImpl are:

    1. Assuming there is just one implementation of this interface, it is clearer by not using abstract class / concrete implementation

    2. If you have a suite of classes (a module) such that several classes access the same "impl" but users of the module will only use the "exposed" classes.

    3. No v-table if this is assumed to be a bad thing.

    The disadvantages I found of pImpl (where abstract interface works better)

    1. Whilst you may have only one "production" implementation, by using an abstract interface you can also create a "mock" inmplementation that works in unit testing.

    2. (The biggest issue). Before the days of unique_ptr and moving you had restricted choices as to how to store the pImpl. A raw pointer and you had issues about your class being non-copyable. An old auto_ptr wouldn't work with forwardly declared class (not on all compilers anyway). So people started using shared_ptr which was nice in making your class copyable but of course both copies had the same underlying shared_ptr which you might not expect (modify one and both are modified). So the solution was often to use raw pointer for the inner one and make the class non-copyable and return a shared_ptr to that instead. So two calls to new. (Actually 3 given old shared_ptr gave you a second one).

    3. Technically not really const-correct as the constness isn't propagated through to a member pointer.

    In general I have therefore moved away in the years from pImpl and into abstract interface usage instead (and factory methods to create instances).

提交回复
热议问题