[HN Gopher] Implementing a class with void* ___________________________________________________________________ Implementing a class with void* Author : azhenley Score : 14 points Date : 2021-08-30 21:31 UTC (1 hours ago) (HTM) web link (web.eecs.utk.edu) (TXT) w3m dump (web.eecs.utk.edu) | prewett wrote: | I'm surprised he doesn't refer to it by name (Pimpl). In C++ it | has the advantage that you can change your implementation and | retain binary compatibility because the size of your class | doesn't change as you add/remove member variables (and maybe more | surprisingly, add/removing virtual functions). If you're going to | use C++, seems like it would be better to avoid the void* by | class C { protected: struct Impl; | std::unique_ptr<Impl> mImpl; }; | | And then define C::Impl in the .cpp file. | anthony_r wrote: | Came here to say exactly that. You can also do this, thought it | looks a little worse it allows for even more flexibility, such | as complete decoupling of Impl from A across different files: | // Forward declaration of Impl. What does Impl do? // | You're not allowed to know. class Impl; class | A { protected: Impl* mImpl; }; | | I've been using this trick but for a different reason - to | reduce the number of #include statements in header files that | are included a lot themselves. | sillycross wrote: | This is a well-known way to achieve separation of definition and | implementation. | | The disadvantage of the method proposed in the article is that, | now everything needs a pointer indirection. | | A solution that fixes the drawback is used by lz4's library | implementation: instead of storing a void star, store a char[] | array of same size as the real struct. (of course, now you have | to manually make sure the struct size are in sync. It's more | error prone, but still not _that_ bad). | guerrilla wrote: | Why not `typedef struct state state_t` in the header file, then | have a `state_t state` in the header file with the `struct | state { ... }` definition in the source file? This is similar | to what I do in C, I don't see why it wouldn't work in C++. | kyralis wrote: | The module that's importing the header needs to know the | state size. To do that, it either needs to see the struct | declaration or be given the explicit size with the array | approach. | [deleted] ___________________________________________________________________ (page generated 2021-08-30 23:00 UTC)