Typecasting structs to hide implementation vs pimpl-idiom
I know about the pimpl-idiom which in C would look something like this:
// foobar.h
struct FooBar {
char *someString;
struct FooBarImpl *pImpl;
};
// foobar.c
struct FooBarImpl {
char *hiddenString;
};
However with typecasting I can get rid of the opaque pointer and reduce the odds that someone messes with the implementation:
// foobar.h
struct FooBar {
char *someString
};
// foobar.c
struct FooBarImpl {
// FooBar members
char *someString
// FooBarImpl members
char *hiddenString
};
In the latter case any function doing operation on FooBar would simply typecast to FooBarI开发者_如何学编程mpl to get access to the 'private' members.
I can see how this would become a problem if, for instance, someone where to add some member to FooBar but not do the same for FooBarImpl. However in my case FooBar will only contain one member and will unlikely change.
Would this be considered good practice or should I just stick with the pimpl-idiom when I wish to hide implementation details?
Thank you.
The compiler is your friend; don't cheat on it by using explicit typecasts, especially between compound types. Stick with the first method, if you forward-declare the implementation struct you'll never have to reveal its contents.
You would have to be very careful when working with code that typecasts between structs:
- You could not create an array of FooBar or provide pointers to such arrays to client code.
- Assigning or memcpy:ing structs (not pointers of them) would require assigning FooBarImpl, not FooBar - otherwise the implementation-specific data would be cut off.
- Looking from the headers, user of the library could erroneously assume that memcpying or assigning or creating FooBar structs is correct - after all, all it seems to contain is basic data that could easily be filled.
精彩评论