r/cpp • u/platisd • Feb 23 '21
The Pointer to Implementation (pImpl) idiom in C++
https://youtube.com/watch?v=lETcZQuKQBs&feature=share13
u/Adequat91 Feb 23 '21
Qt is a good example of proper pimpl implementation and benefits.
9
u/NilacTheGrim Feb 23 '21
Yep. This ^
Note that they maintain 100% binary backwards compatibility within the same major version -- this despite them radically changing around the guts and internals or adding a plethora of features. Pimple is the only real way to do this in C++.
7
u/PancakeFactor Feb 23 '21
I love pimpl and honestly think it gets a bad rap. It lets me:
-Hide my implementation away
-Put all of the relevant data in the same file as my implementation ( no more jumping back and forth between header and cpp )
-Get ABI stability
-AND not really get a performance hit? ( compilers tend to optimize the dereference out with optimization flags ).
Idk why people hate it so much. I use it all the time.
9
u/quicknir Feb 24 '21
There's no planet where pimpl, at least done naively with unique_ptr, isn't a huge performance hit in many cases. Compilers can't magic this out. It changes the memory layout, good memory layouts are half of why people use C++.
2
u/dandomdude Feb 24 '21
So could we say pImpl is good for objects which rarely get created/destroyed? Like in the video, a Gyroscope class probably has the lifetime as the program as it'll always be reading the sensor?
2
u/quicknir Feb 24 '21
Yeah, as a general rule of thumb if there's few of the object and they aren't created and destroyed in the hot path, it's generally fine to pimpl.
1
u/dandomdude Feb 25 '21
Oh hey, I just realized you're the
wise_enumguy, thanks for the great work!1
u/quicknir Feb 25 '21
Ah thanks, not sure I deserve it, so many headaches trying to get it to work on windows, and I've been a bit negligent, but I'm glad at least someone is using it happily!
4
4
u/lord_braleigh Feb 23 '21
I think it’s because interfaces provide a more user-friendly solution to the same problem.
3
u/brenoguim Feb 23 '21
Dynamic allocation through. It's possible to do pimpl without heap allocation, but people rarely do it. It's cluncky. I don't think compilers can optimize pimpl away too. Only if you're using LTO, but you still have to dereference the pointer to get to the data.
3
u/ReDucTor Game Developer | quiz.cpp-perf.com Feb 24 '21
You had me until the last point, the compiler isn't going to be able to optimize away the dynamic allocation that occurs in most pimpl implementations, it isn't going to be able to optimize away the additional dereference, instead of just having one cache line for your data you have 2, one which has just a pointer the other which has your data.
Sure there are ways to do pimpl where you don't have to do extra allocations and additional indirection, but those increase complexity and aren't very common.
While I don't have any numbers on me, I can pretty much gurantee that the typical implementation of pimpl is going to be massively slower, go create 10k instances of a pimpl class and compare it to 10k instances of a non-pimpl class, it should be very easy to see the difference in construction, destruction and usage.
Sure you can build a micro-benchmark that focus on a single instance comparing against a single instance and the indirection might be insignificant, but this really does not demonstrate the fact that things aren't always in your cache, your application is typically much bigger then the cache all your objects can't live there.
I'm not against pimpl, but it's very far from a perfect tool, especially for who cares about performance, just pick the right places to use it, don't abuse it.
1
u/Dean_Roddey Feb 24 '21
In the vast majority of code it will make no difference at all.
3
u/ReDucTor Game Developer | quiz.cpp-perf.com Feb 25 '21
I would say instead the vast majority of code doesn't need pimpl
1
u/Dean_Roddey Feb 25 '21
Depends on what you are trying to accomplish. As others have pointed out, if stable ABI over time is important, then the majority of your code may need it.
2
u/AntiProtonBoy Feb 23 '21
I don't hate it; I used it often myself. However, some of the negatives I can think of are mostly the extra maintenance burden & costs associated with the pimpl idiom. In some cases you're wrapping one interface with another. And there is also the cost of dynamic allocation for the implementation itself. This leads to the need of tracking the pointer and implementing machinery for constructing/copying/moving/assignment/destruction. Some of those are solved with smart pointers, to some extent, but all of this work doesn't feel idiomatic compared to a pure interface solution. For example, Objective-C does this kind of stuff really well.
1
u/NilacTheGrim Feb 23 '21
Same here. They are nubs that don't know any better. I never met a seasoned C++ guru that didn't know the value of when to use pimpl.
You don't have to use it EVERYWHERE or ALL THE TIME. But keep it in your toolkit and break it out when it makes sense and improves maintainability. Or when you need ABI stability.
5
u/PancakeFactor Feb 23 '21
Definitely dont use it for everything. There are concrete cases where it makes no sense, but its definitely more useful than people give it credit for.
5
u/kalmoc Feb 23 '21
Pimple wouldn't be necessary, if we could just forward declare class interfaces.
10
u/Benjamin1304 Feb 23 '21
How client code could know an object's size if it only has its interface forward declared?
I can't see how it could work without the compiler making automatically an hidden pimpl in this case
4
u/kalmoc Feb 24 '21
Two possibilities:
The client code wouldn't know and would have to use factory functions + smart pointers/handles + clone functions (albeit non-virtual). That would put us at least on par with a opaque c-style interface, just with more convenient syntax. It would also require the same amount of dynamic allocations as Pimple, but - for better or for worse - couldn't hide them from the user.
The size gets specified as part of the declaration and the compiler verifies that it is correct when it sees the definition. That would allow the type to be handled like a regular value type and - contrary to pimple- wouldn't even introduce dynamic allocations.
1
u/ReDucTor Game Developer | quiz.cpp-perf.com Feb 24 '21
A larger reorg of the way in which compilers work could probably do it...maybe something like modules might solve the issue.
1
u/logicchop Feb 24 '21
Isn't that precisely a virtual interface?...
2
u/kalmoc Feb 24 '21
No. virtual interfaces result in indirect function calls and things like the copy constructor can't be virtual
1
2
u/helloiamsomeone Feb 23 '21
I recently used pimpl for my CMake static/shared library example that I also posted to this sub.
It's a pretty nifty construct, but MSVC emitted a warning about unique_ptr not having the necessary annotation for dll import/export, so I had to use a raw pointer instead.
1
u/14ned LLFIO & Outcome author | Committee WG14 Feb 24 '21
You can safely ignore that MSVC warning for anything it complains about which is defined entirely in header only. Use pragma warning disable to suppress.
1
u/beedlund Feb 24 '21
What are peoples thoughts on pimpl vs. non-virtual interfaces (https://en.m.wikipedia.org/wiki/Non-virtual_interface_pattern)
I often use nvi in public interfaces over pimpl but only because the pimpl presence always feels a bit like an eyesore (not the best way to make decisions but there you go).
Are there particular advantages either way?
0
u/charlesbeattie Feb 23 '21
Maybe take a look at https://github.com/hpesoj/indirect Which is a better tool than unique_ptr.
1
u/platisd Feb 25 '21
Are you perhaps referring to the same thing as this issue: https://github.com/platisd/cpp-pimpl-tutorial/issues/1
Very interesting nonetheless!
0
Feb 23 '21
[deleted]
17
u/spanishgum Feb 23 '21
Pimpl doesn’t have to be used for polymorphism. Pimpl is just a way of speeding up compile time if a header gets included in a lot of places, and that include is big.
If you’re using polymorphism with 1 derived class to get the compile time advantage, then I suppose you’re cornering yourself to do dynamic allocation of the base class everywhere. You can’t have a vector<Base> because of the slicing problem, so you’re stuck with vector<Base *>.
With pimpl you’ll have dynamic alloc internally, but at least calling code doesn’t have to deal with that.
In the end you should probably ask yourself first, is any of all that even necessary? Is your project that big? And are these included really that unstable?
34
u/parkotron Feb 23 '21
While they can accomplish the same goals in this context, pimpl and pure interfaces feel very different to me.
If I'm reading code an I see a pimpled class, I think "This is a class that, for whatever reason, wants to keep its implementation details from those who use it." Maybe it's nasty third-party headers, maybe it's ABI stability, maybe it's compile times, but frankly it's none of my business as a consumer of the class. It's more of a craftsmanship issue than a design issue.
If I'm reading code an I see a pure interface and a factory function, I think "There are one or more classes out there that meet this interface, but for whatever reason this library doesn't give me control over which one I get to use." Maybe the actual type I get depends on some global configuration, maybe it depends on my operating system, maybe they've just left themselves open to future expandability, but as a consumer I can't and shouldn't worry about the specific type and should just write code to the interface. This feels a lot more like library design issue than just a coding trick.
I guess it's kind of like
classversusstruct. They can be made to do the exact same thing, but as a reader I tend to come in with differing sets of assumptions.5
u/Rotslaughter Feb 23 '21
The abstract class approach comes at the expense of virtual calls, which might affect performance in code that is often (and I mean millisecond level often) executed.
9
u/tecnofauno Feb 23 '21
ABI stability is one clear advantage of pimpl. You can add members to the private implementation without impacting binary compatibility.
Qt for example use the pimpl pattern extensively.
0
Feb 23 '21
[deleted]
6
u/tecnofauno Feb 23 '21
If by interface you mean pure abstract classes without any data member and only virtual methods, then it's true but adding, changing or removing anything to the interface will break the ABI.
Also you lose value semantics.
Pimpl can be used to preserve binary compatibility on concrete classes and can be used to implement movable and copy-on-write objects with the benefits of value semantics.
1
u/Full-Spectral Feb 24 '21
That latter point is important. So a bitmap class can have value semantics, but never pay the price of moving all of that bitmap data around.
Of course the gotcha there is that now you have to explicitly request deep copies when they are needed, and forgetting to do so can cause lots of weirdness. There's no way to win ultimately.
8
u/SlightlyLessHairyApe Feb 23 '21
pimpl is often implemented in terms of pure interfaces (ABC).
But you can’t use the constructor on an ABC, you need either a factory method or a concrete class somewhere. Having a factory class that produces objects that implement an ABC is isomorphic to pimpl when there is only one implementation.
0
Feb 23 '21
[deleted]
1
u/SlightlyLessHairyApe Feb 24 '21
If there’s only one implementation than pimpl avoids one virtual function table lookup.
In practice this is not a huge deal.
4
u/logicchop Feb 24 '21
I use a pimpl style approach for creating a shim layer on some other library I don't want included in my "user facing code." I use pimpl instead of an interface because I like to add separate operations that consume my shim type, but under-the-hood rely on the single known implementation and just uses the library code. So, in my case, I know that there is only one implementation type, and I can coordinate a lot of other operations around it. If I changed the underlying implementation, the operations would also have to change, and there is no feasible generalizable interface for what is there.
1
u/platisd Feb 23 '21 edited Feb 23 '21
I'd also always side with pure abstract classes over pImpl unless I'd want to maintain ABI compatibility and this wasn't possible or guaranteed in any other way.
Otherwise no, I'd stay clear of it since I personally find it harder to understand, maintain and test.
3
u/Full-Spectral Feb 24 '21
As others have pointed out, the PIMPL scenario allows you to maintain value semantics on the outer class. Using abstract classes doesn't. That can be a significant consideration.
2
u/oracleoftroy Feb 26 '21
If you are using a pimpl or a virtual interface to hide implementation details, pimpl can be faster. You will almost certainly have one pointer indirection in both cases, and with the abstract class, you also have the vtable lookup.
It's been a year or two since I last measured, but I recall the same performance for both pimpl and pure virtual interfaces in MSVC, and a slight improvement with pimpl in gcc and clang.
So from my perspective, it comes down to slightly more performance but having to write the implementation twice for a pimpl, or having to write the implementation 1 1/2 times with the interface + implementing class (which does honestly feel more straight forward and less work) but having extra indirection that might slow things down.
All that said, I try to avoid both where possible, and tend to favor pimpl unless I need multiple implementations, mostly because I highly favor value semantics. But I really ought to remeasure. Compilers have been getting better about optimizing final classes and methods.
3
u/CrazyJoe221 Feb 23 '21 edited Feb 23 '21
I will always prefer interfaces over pimpl.
It allows the tools to actually understand what you're doing. So the compiler can optimize the overhead away completely (with LTO and
finalat least), an IDE can help with an "implement interface" action for example and the debugging experience was also better for me.You also potentially save a heap allocation that can't be optimized away otherwise. And things get nasty if you need inheritance, see the dance Qt has to do internally.
0
u/johannes1234 Feb 23 '21
For the compiler to do that the compiler has to see the implementation. A point why people however is used is to hide the implementation (improving compile times, not having to provide the headers with the type declarations for members etc.) In such a case only the linker might do link time optimisation.
3
1
u/Ok-Impact-5972 Feb 23 '21
I think this is a important point to make. When pimpl-shines is when you need to handle a class that you do not have an interface for, or do not want to store as a pointer.
However: Often when for example using a factory-function or a builder to obtain a interface pointer to your class, you never have to handle the actual class. In that case it is a total waste to pimpl the class.
0
Feb 23 '21
[deleted]
4
-3
u/Full-Spectral Feb 24 '21
You could have gotten so many other things done in that 8 seconds. I feel your pain...
74
u/stilgarpl Feb 23 '21
I hope we can forget about pimpl when modules are finished. Pimpl feels like a workaround and shouldn't be needed when we have private module sections.