13 comments

  • amluto3 hours ago
    I have a little class called EImpl that is kind of like std::indirect except that it embeds the impl instead of pointing to it. It takes three template parameters: an embedded struct, a size and an alignment. It static_asserts that the embedded struct fits in the size and alignment, and it embeds it with approximately zero overhead. It’s about as easy to use as any other pImpl technique.
    • knorker57 minutes ago
      But if the pimpl size grows too big, you&#x27;re forced to break ABI?<p>And before it grows too big, it wastes memory. For your use cases it may not matter, and the saved pointer indirection may be more important, but maybe the person who has a million item vector of objects doesn&#x27;t appreciate a 300% &quot;just in case&quot; memory overhead. The overhead may also hurt cache hits.<p>If you&#x27;re doing this to save the pointer indirection, you should benchmark it for every use case, since negative cache effects may dwarf that gain.<p>Then again, extra padding can also help performance, for some workloads (especially multi threaded read&#x2F;write against a vector of objects).<p>So without further context, there&#x27;s no way to say if your way hurts or helps. It&#x27;s certainly not a general solution.
      • StilesCrisis40 minutes ago
        &quot;Breaking ABI&quot; isn&#x27;t an issue unless you can&#x27;t compile your code anymore. It&#x27;s pathetic that C++ has been so hamstrung over ABI that we&#x27;re willing to stop improving.
  • Panzerschrek3 hours ago
    &gt; Never null: it always holds a value, except in the moved-from state<p>I am wondering why C++ can&#x27;t implement &quot;non-null&quot; unique_ptr version in the same way? As I know, that the main argument against implementing it is, that it&#x27;s can&#x27;t be done, since move-out unique_ptr still can be null.
    • cenamus3 hours ago
      The C++ core guideline support library has it.<p><a href="https:&#x2F;&#x2F;github.com&#x2F;microsoft&#x2F;GSL&#x2F;blob&#x2F;main&#x2F;docs&#x2F;headers.md#user-content-H-pointers-not_null" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;microsoft&#x2F;GSL&#x2F;blob&#x2F;main&#x2F;docs&#x2F;headers.md#u...</a><p>What do you mean by move-out unique_ptr? That the not_null ptr type would ne null after it&#x27;s been moved?<p>In that case that&#x27;s just a plain usage error, same as how you could memset it to null.
  • ryani56 minutes ago
    Sadly, you can&#x27;t easily do the full pimpl idiom in C++.<p>The pimpl idiom is a C idiom where a header declares an opaque structure and prototypes of functions that take pointers to that structure. In C the OP example would look something like<p><pre><code> &#x2F;&#x2F; widget.h typedef struct Widget_t Widget; &#x2F;* opaque! *&#x2F; Widget* Widget_Create(const string* pName); Widget* Widget_Clone(Widget*); void Widget_Destroy(Widget*); void Widget_click(Widget*); int Widget_clickCount(const Widget*); const string* Widget_label(const Widget*); &#x2F;&#x2F; widget.c struct Widget_t { int clicks; string *name; }; &#x2F;&#x2F; ... implementations of the functions from the .h ... </code></pre> In particular, in C `Widget` directly has `clicks` and `name` as fields.<p>But in c++ we like to use methods on objects, and in order to do this, you need the class declaration in scope, which means your current compilation unit needs to have seen all of Widget&#x27;s data members. In practice this means if you try to use &quot;pimpl&quot; in C++, you do something like the OP where there is a pointer to an opaque type inside your class.<p>However, this is <i>not</i> the same thing. Methods are called with a `this` pointer, which means every access to the internal structure adds a second pointer dereference. This is why this isn&#x27;t the true pimpl -- it wastes an extra deref on every access.<p>You can get true pimpl in current C++ but it&#x27;s a lot of boilerplate and heavily relies on compiler inlining. An implementation of the example from the OP: <a href="https:&#x2F;&#x2F;godbolt.org&#x2F;z&#x2F;6EznxeG1n" rel="nofollow">https:&#x2F;&#x2F;godbolt.org&#x2F;z&#x2F;6EznxeG1n</a> . In practice this is too much work, hard to read, and so nobody does it.<p>For the c++ standards committee: please add an &quot;opaque class&quot; feature where the class can only define non-virtual method prototypes. Then the full class declaration, in the associated cpp file, could include its parent classes, actual data layout, and function implementations.
    • dooglius4 minutes ago
      Completely agreed, but in fairness to the c++ standards committee, this is solved from a standards perspective by c++ modules
  • zabzonk4 hours ago
    Hmm. Do people use PIMPL that much (I have used it, but rarely) that we need std library support (and testing, documentation, understanding)? Just asking.
    • dvratil4 hours ago
      It&#x27;s often used in libraries where you need to guarantee ABI compatibility. Fixing a bug or implementing a feature may require adding a new member into the class, which would change its size (thus break ABI compatibility). PIMPL is the typical solution here, since the inner&#x2F;impl class is not part of the public ABI.<p>I also like to use it sometimes to &quot;hide&quot; private methods and their documentation into PIMPL, so the public header is kept clean.
      • zabzonk4 hours ago
        &gt; PIMPL is the typical solution here, since the inner&#x2F;impl class is not part of the public ABI.<p>Yep, that&#x27;s what I&#x27;ve used it for. Didn&#x27;t find it too difficult to implement it myself, but I guess every bit of convenience&#x2F;bug avoidance helps.
    • flohofwoe4 hours ago
      This std::indirect thingie looks more like a general helper for any data &#x27;dangling off&#x27; an object, not limited to pimpl.<p>Not sure how much pimpl is used in reality, but it&#x27;s a pretty ok solution to speed up build times (apart from unity builds), because it avoids having to include headers that are only needed for the private state into the public interface header.
    • feverzsj4 hours ago
      Yes, if you actually care compile times.
      • RossBencina3 hours ago
        Indeed. I primarily used PIMPL when I want to avoid polluting public header files with implementation detail #includes in cases where forward declarations are impossible or unwieldy and inline methods are irrelevant.
      • einpoklum3 hours ago
        My approach to reducing the compile time of code which uses a class is moving the functionality out of the class and into standalone functions; or at least moving the method definitions into a non-header `.cpp` file.
      • otabdeveloper43 hours ago
        Lucky for you, I don&#x27;t.
    • green7ea4 hours ago
      I remember using it all the time for the Windows headers because they pollutes the compilation unit like you wouldn&#x27;t believe — the rule was to only include them in c&#x2F;cpp files.
      • maccard3 hours ago
        We put<p><pre><code> #define WIN32_LEAN_AND_MEAN 1 #include &lt;windows.h&gt; </code></pre> In precompiled headers to solve that particular problem.
        • silon422 hours ago
          That&#x27;s kind of a hack, still best only used in implementation files, not headers.
          • whizzter2 hours ago
            The irony is that including&#x2F;using many standard c++ headers is far far more expensive than including a lean windows.h these days.<p>To make hobby-coding fun, i use a mstdp.hpp that implements &quot;naive&quot; versions of unique,shared,function,etc that compiles faster than including just one of the std versions (and yes, MSVC versions of those libraries seem to be excessivly complex).
    • neonz804 hours ago
      They didn&#x27;t add PImpl support, they added std::indirect which can be used for PImpl among other things.
    • seanhunter4 hours ago
      Back when I used to write C++ it was used all over the place. Admittedly that was a log time ago.
  • whizzter1 hour ago
    Where are we with modules, isn&#x27;t pimpl there largely to avoid costs related to including the world?<p>I was pondering on why he was putting the defaulted methods in the cpp, any particular reasons?<p>I did realize that the indirect version is required to be in the cpp since the header won&#x27;t know how to copy without knowing the definition of the impl class.
    • ghosty1411 hour ago
      pimpl helps more since its trivially implementable in existing codebases while modules are a much bigger pain.
    • cemdervis1 hour ago
      pimpl also helps to keep data structure layout stable, e.g. Qt&#x27;s d-pointer convention
    • knorker1 hour ago
      pimpl also makes it much easier to make changes without breaking ABI. E.g. shared libraries.
  • 3form4 hours ago
    This looks great indeed - I wonder if there are any particular gotchas, though, as things often are in C++next land.<p>With many of the features coming into the language over time, I kinda wish that a bit more restricted subset of it eventually becomes a thing, but I know in practice it might as well be a completely different language. That, and I expect that still many other things have not been resolved as well as they are elsewhere, such as build system and dependency management (although I haven&#x27;t touched this stack for a while now, so I would love to be surprised).
    • torginus21 minutes ago
      The gotcha is that this is a 90s C pattern, and software that actually needed this has been written for 3 decades by now
    • dingaling9114 hours ago
      &quot;Holds a value, except sometimes&quot;
  • smallstepforman1 hour ago
    Oh god, what monstrocity have we created?!?<p>All this complexity follows unique_ptr and copy constructor madness.<p>Anything with pointers with ownership should never be copied - period. Reference pointers - OK if scope&#x2F;lifetime is known.<p>Can we have c++11 lite?
  • einpoklum3 hours ago
    The example is problematic, in that:<p>1. click() should not be a member of the widget. A widget does not click; a user clicks a widget. A click can change a widget&#x27;s state, but the state might change because of other effects, e.g. pressing a key when the widget is focused. But then, that&#x27;s just one of the issues with treating UI widgets this way.<p>2. More to the point - clickCount. If this is a button, it shouldn&#x27;t keep a record, or aggregate, of its clicks within it; and if it&#x27;s a widget where this does really matter, like a range control where more clicks mean a value that goes farther along the range - you still would not keep the count of clicks, but the current position. Statistics about the interaction with an object should not be part of the object itself. At most it might be legitimate to have, say, a Widget class, a template like &lt;class Stats&gt; StatisticsTracker , and then class TrackedWidget which uses that as a mixin, i.e. inheriting both Widget and StatisticsTracker&lt;ClickStats&gt;. And that&#x27;s already stretching it beyond what I would find reasonable.<p>3. Having something named is another aspect of objects which may be a good fit for a mixin class.<p>Anyway, an &#x27;indirect&#x27; type for objects you don&#x27;t know the definition of sounds nice.<p>A few more nitpickis about the example:<p>1. Instead of explicitly applying the rule-of-0 with `= default` for the copy&amp;move ctor&amp;assignment and the destructor - just _don&#x27;t_ write anything:<p><pre><code> class Widget { public: void click(); int clickCount() const; std::string label() const; private: struct Impl; std::indirect&lt;Impl&gt; pimpl_; }; </code></pre> and that&#x27;s the beauty of the rule of 0.<p>2. Why return an std::string for the label? The label() method should return an std::string_view
    • spacechild12 hours ago
      This is just a simple example, therefore nitpicking on the semantics of the Widget methods is a bit silly.<p>&gt; 1. Instead of explicitly applying the rule-of-0 with `= default` for the copy&amp;move ctor&amp;assignment and the destructor - just _don&#x27;t_ write anything:<p>The blog post explicitly explains why this doesn&#x27;t work. You have to define these methods in the source file because they need to see the definition of the Impl struct.
    • murderfs2 hours ago
      &gt; 2. Why return an std::string for the label? The label() method should return an std::string_view<p>This only works if it&#x27;s always the same value. This doesn&#x27;t work if the label is for example, set to `std::to_string(clickCount())`
  • z0ltan1 hour ago
    [dead]
  • Yomguithereal3 hours ago
    [flagged]
  • shevy-java4 hours ago
    C++ is getting more and more complex. It used to be said that people use only a small percentage of it when writing C++, but I am beginning to think that the cake is a lie here.
    • pjmlp3 hours ago
      Besides being a common idiom, for how many warts C++ might have, no one is rewriting LLVM, GCC, V8, JVM&#x2F;ART and .NET runtimes, CUDA&#x2F;Metal&#x2F;DirectX, Unreal, Godot,.... into something else, RIR is not happening there.<p>People will contend themselves with &quot;C++ the good parts&quot;, helped by clang-tidy, PVS, MSVC analyse, and move on.
    • feelamee4 hours ago
      where &quot;more and more complex&quot; do u see in this article? This is a basic C++ idiom, which constantly used by developers
      • seanhunter4 hours ago
        Yes. If anything, this is taking a complex yet common idiom and making it simpler.
        • usrnm3 hours ago
          Is it actually simpler, though? The unfortunate reality of this world is the fact that C++ is not the latest standard of the language or the newest shiny library, it&#x27;s all of them at the same time. Adding a new way of doing the same thing decreases complexity only if you migrate all of the existing code, which nobody ever does.
      • dvratil4 hours ago
        I think the parent&#x27;s point is that we started with raw pointers to implement PIMPL, then we had std::unique_ptr, and now we have std::indirect. So there are now three different ways how PIMPL can be implemented, each has its gotcha&#x27;s and subtle differences that one needs to keep in mind. In large codebases you will now have to deal with all three solutions being used, depending on how old the code is.
        • gblargg4 hours ago
          The point of each improvement is fewer easily-made errors. Having implicit deep copying handled avoids lots of errors with manually implementing it the oldest way.
          • jstimpfle2 hours ago
            Well that&#x27;s a lie. I&#x27;ve long been back to raw pointers and it&#x27;s by far the easiest way to do it. All of Pimpl, unique_ptr, and whatever other clever mechanism (I&#x27;m not even looking at std::indirect anymore) just aren&#x27;t really ergonomic.<p>Nobody needs &quot;deep copying&quot;, ever. It&#x27;s not even well defined what it should mean (i.e. how deep etc.). It&#x27;s purely a theoretical problem with no good practical (one-fits-all) solution. The only practical way is to copy what you need copied, when you need it. Done.
      • konstmonst4 hours ago
        std::indirect looks for me like another pointless c++ thing that already works with forward pointer declaration. You can add it to another ton of pointless things C++ adds without fixing the old ones. The issue with c++ is that it is so big, that everyone uses some kind of dialect of it and the fancier it gets, the less readable it becomes and the more magic happens behind the curtains. A developer of a C++ codebase now has to learn a specific meta language of this codebase. Fuck that, I have enough languages and their idiosynchronies to remember for my work now. After using Go for a pair of years returning to C++ is like coming back to a big archaic mess. I&#x27;ll just go learn Rust instead and forget all those new useless C++ templates like std::indirect
        • wwind1233 hours ago
          I think it&#x27;s kind of awkward either way. The standard committee keeps adding new features to the language to address common pain points in the industry. But many people don&#x27;t have that much time to learn the new features, and hates it when seeing something in the code but can&#x27;t intuitively understand what it&#x27;s doing. I once witnessed a 10+ year C++ coder (that had been immersed in some old C++ code base for many years) seeing a piece of C++14 code for the first time -- he said it reads like an entirely different language, not the C++ he&#x27;s familiar with at all.
          • einpoklum3 hours ago
            &gt; But many people don&#x27;t have that much time to learn the new features<p>Because they spend so much of their time struggling with the pain points of the older code.<p>&gt; but can&#x27;t intuitively understand what it&#x27;s doing<p>For (most?) new vocabulary types, it is rather intuitive to understand what they do. optional, variant, indirect - you may not remember the details by heart immediately, but you get the general idea and expect that they would behave in some reasonable way. And mostly, they do. That&#x27;s not to say they&#x27;re perfect: I feel like vomiting looking at std::variant&#x27;s and how you have to work with them, as opposed to a proper case classes &#x2F; algebraic union types in the language itself. And yet - when someone puts one in their class, instead of a bunch of code in a bunch of methods, you know what&#x27;s going on. It does &quot;read like a different language&quot; somewhat, and that&#x27;s good. The nicer language has been struggling to get out, as the saying goes.
            • jstimpfle2 hours ago
              Pretty much all the C++ features I&#x27;ve used are good enough to write some toy code snippet, but it&#x27;s hard to use them to good effect at scale without causing massive problems.<p>Even classes are an instance of this, they were to solve some perceived problems, but they created much bigger issues, such as readability issues and introducing many more compile time dependencies.<p>PIMPL wasn&#x27;t even a C++ feature but an idiom pushed by some people. It is next to unusable because you have to duplicate the API and write all the call forwards.<p>One problem with std::unique_ptr for example is that there is no ergonomic way to use it to hide implementations. The reason is it relies on destructors and to use destructors the class definition needs to be visible.
  • coffeeaddict14 hours ago
    This is actually useful, but despite it is another extra thing you will <i>have</i> to remember when reading C++ code. I guess with LLMs things aren&#x27;t so bad.
    • skrebbel4 hours ago
      Why? It’s still the good (bad) old pimpl pattern. It just got a bit shorter. When reading you dont even need to grok “std::indirect”, you see the word pimpl and you know what’s going on.
    • MaPi_3 hours ago
      I don&#x27;t really get why people keep repeating the &quot;C++ is too big&quot; complaint together with the implication that you need to remember the entirety of the standard library. In comparison Java has networking, GUI framework and even MIDI in its standard libraries. Is it because C++ is more closely related to C which library is so small that it barely contains anything useful? I much prefer code that uses a library feature rather than yet another poorly implemented and not documented hand rolled version of it.
      • dooglius3 hours ago
        Networking, GUI frameworks, and MIDI are presumably all self-contained and you would not need to be familiar with them except when working on networking, GUIs, or MIDI files, respectively. This is a general-purpose thing that could show up in any c++ code.
    • einpoklum3 hours ago
      You need to remember _less_, rather than more, when you use this kind of vocabulary types. Think about std::optional. Before that (and if you didn&#x27;t write something like it yourself), you had to, for each class, remember the bespoke semantics of when and how it represents the lack of some members, and you would have to have non-defaulted ctors, move assignments and dtors, and then whenever you used that class you would need to think about what those custom method do, which might be different than other classes which have optional members. Now you just tell yourself &quot;oh, it just has an optional member, no biggie&quot;. Look at my comment above regarding how short the implementation of Widget becomes when you squeeze the juice from having the rule of 0.
  • AnaSpelunker1 hour ago
    I thought C++ is unnecessarily complex, and then I see Rust following the same pattern... I&#x27;ve just thought of a complexity metric that would calculate the ratio of alphanumeric characters to punctuation.