Is the pImpl idiom really used in practice?

后端 未结 11 1301
渐次进展
渐次进展 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:31

    It seems that a lot of libraries out there use it to stay stable in their API, at least for some versions.

    But as for all things, you should never use anything everywhere without caution. Always think before using it. Evaluate what advantages it gives you, and if they are worth the price you pay.

    The advantages it may give you are:

    • helps in keeping binary compatibility of shared libraries
    • hiding certain internal details
    • decreasing recompilation cycles

    Those may or may not be real advantages to you. Like for me, I don't care about a few minutes recompilation time. End users usually also don't, as they always compile it once and from the beginning.

    Possible disadvantages are (also here, depending on the implementation and whether they are real disadvantages for you):

    • Increase in memory usage due to more allocations than with the naïve variant
    • increased maintenance effort (you have to write at least the forwarding functions)
    • performance loss (the compiler may not be able to inline stuff as it is with a naïve implementation of your class)

    So carefully give everything a value, and evaluate it for yourself. For me, it almost always turns out that using the pimpl idiom is not worth the effort. There is only one case where I personally use it (or at least something similar):

    My C++ wrapper for the linux stat call. Here the struct from the C header may be different, depending on what #defines are set. And since my wrapper header can't control all of them, I only #include in my .cxx file and avoid these problems.

提交回复
热议问题