r/cpp • • 29d 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

Show parent comment

9

u/pavel_v 28d 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 28d 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 28d 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 28d 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 25d 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++?