r/cpp • • 26d ago

How I design C++ classes

https://rafb.eu/blog/cpp-class-design/

This is my first ever blog-post, any feedback is welcome! ofc, no AI got used.

66 Upvotes

46 comments sorted by

View all comments

13

u/decapod2005 26d ago

Idk about pimpl idiom in 2026. Sure it's good for trading runtime for compile time performance (among other things), but when people reach for C++, they are usually interested in trading in the opposite direction. It's certainly a useful technique to know, but it should never be the default way how you write classes.

// virtual for testability

This is one of the weirdest statements that I still see made with some frequency. It implies two pretty wild claims:

  • Non-virtual functions are not testable.
  • You should degrade the performance of your actual production code in favor of the tests that you want to write.

Neither of these are true. Just come up with a proper test that doesn't require the function to be virtual.

7

u/NeuroSynchroBonding 25d ago

Pimpl is pretty useful to keep ABI compatibility if the project requires it.

4

u/decapod2005 25d ago

Yeah like I said, it has its uses. If you need a class with stable ABI, great, use it. But even if you need that for some classes in your library, most will still be internal and not need it. So it is not great advice to generically say "Here is how you design a good class" and then show pimpl or a couple layers of oop.

9

u/pavel_v 25d ago

You don't need to introduce runtime performance when using some forms of PIMPL. We've used something like the below one and as far as I've checked the assembly in few of our use cases, it completely disappears and there is no indirection introduced. Of course, there is a tradeoff - there is no ABI stability in this case. If the requested Size or Alignment changes this will cause/need recompilation.

template <typename T, size_t Size, size_t Align = alignof(void*)>
class pimpl
{
    alignas(Align) unsigned char buff_[Size];

public:
    template <typename... Args>
    explicit pimpl(Args&&... args) 
    { new (buff_) T(std::forward<Args>(args)...); }
    ~pimpl()
    {
        static_assert(Size >= sizeof(T));
        static_assert(Align >= alignof(T));
        get()->~T();
    }
    // copy/move ops
    // ...

    T* get() { ... }
    T* operator->() { ... }
    T& operator*() { ... }
};

2

u/decapod2005 25d ago

This just looks like a stack object with extra steps? You still need the explicit dependency to the type that you want since you have to supply it as a template parameter. So as far as I can see it doesn't achieve anything that the pimpl idiom does.

9

u/pavel_v 25d ago

No, you don't need to include the implementation of the T in the header. You just need forward declaration of T. Like:

// In foo.h
class foo
{
  pimpl<class foo_impl, 8> impl_;
    
public:
  foo();   
  ...
}

and then in foo.cpp


class foo_impl
{
 // Implementation of foo_impl
 ...
};

foo::foo() 
{}

...

3

u/decapod2005 25d ago

I see, it works because we are telling the compiler explicitly what the size and the alignment is. That's fair enough.

1

u/victor-s8n 22d ago

Uf, don't do that. Keep it simple. Imagine you onboard a new dev to that codebase.

Is the trade-off worth it? How much faster is such code vs simple school-style c++?

2

u/victor-s8n 22d ago

You can set the impl methonds to `final` https://en.cppreference.com/cpp/language/final . In doing so the compiler can reason better about the v-table.

Over the past years I learned that 95% of the code is not executed very often. There is a 5% hotpath, but you, know, measure first. For the other 95% of the code, it's about maintainability, testablilty, and yes, compilation-time.

yes "Non-virtual functions are testable".

It's C++.

EVERYTHING is possible, which leads to projects being unmaintainable. I think this makes C++ unpopular. This thinking of the few nanoseconds that one can strip off, by optimizing a `virtual`. Code that only runs once when eg parsing a config-file.

1

u/decapod2005 22d ago

final keyword only helps when you are not actually doing polymorphism. As long as you access the impl function through the base class interface, the compiler can do nothing.

Measuring is important to find bottlenecks, but they become buch harder to find when your first, default approach is already pessimized. When every functionality has to go through hundreds of virtual function calls, you won't see any improvement if you optimize one of them.

It's not a good idea to by default add abstractions that you do not need.

2

u/IronOk4090 25d ago

This seems to be a Java-centric mindset, to make every class support virtual dispatch.

1

u/Life_Sink9598 25d ago

Yes, but in the Java case you'll get open, inlineable, calls instead of virtual dispatch (thx to JIT).

1

u/radical_ax1s 23d ago

my interpretation of "virtual for testability" is that another client class may depend on the service_health_checker. unit-testing that client class requires mocking a service_health_checker, and I guess you could do it by subtyping. hate this though, such a client class should depend on a pure abstraction (ABC / Concept) as per DIP