5 ms·
It is not an industry standard way. It is not a sensible way. It is not even a C way. As others have said, there's no reason whatsoever to use void* here. Just
by cjensen 5y ago
It is not an industry standard way. It is not a sensible way. It is not even a C way.
As others have said, there's no reason whatsoever to use void* here. Just declare the struct without defining it in the header. Then only define it in the C file. C is fine with pointers to structs which are merely declared but not defined.
- kazinator 5y agoIt is a de facto standard in that it is fairly widely documented and actually done. It's not in any ISO or IEEE standard or anything of the sort. There is almost no reason whatsoever to use void * anywhere other than to write a declaration that is compatible with another one which uses it. (A pointer to any object is better implemented as a typedef for unsigned char *. This requires a cast in both directions, thus it is safer. At the same time, it is more convenient when you actually want to work with the memory as such: you have bytewise arithmetic and dereferencing.) > C is fine with pointers to structs which are merely declared but not defined. Particularly if the secret object is a struct/class then this certainly improves the code (and when the secret isn't such a thing, it can probably be made into one: e.g. a secret array of integers can probably just be a a struct containing an array, possibly a flexible one). Numerous unsafe casts are thereby eliminated. But it makes no material difference to its organization or semantics. It's still the same PIMPL pattern.
- not2b 5y agoIt (using a void pointer) is a worse way of doing PIMPL. Give the class a name, but don't expose its implementation (use an opaque class). This means that within the file or files that have access to the full implementation the correct type is present and no casts are needed. Well, what if the actual class is a template? No matter, you can derive a class from a template, as in: header: class Impl; implementation: class Impl: public std::vector<SomeType> { ... }; People who don't do this and use void* wind up with an implementation that has lots of casts in it, and it's easier to introduce bugs, especially once you get to the point where you have two or more hidden implementations.
- deleted 5y ago[deleted]
- hactually 5y agoUsed to teach C++ - doing it this way is absolutely _not_ how to do or use the PIMPL idiom [0]. Declaring a private and opaque forward decl is very different to VOID* all the things. [0] https://en.cppreference.com/w/cpp/language/pimpl https://en.cppreference.com/w/cpp/language/pimpl
- kazinator 5y agoThe term ”PIMPL” itself (by far) predates all the cruft shown there.