Search code examples
c++ctypedefopaque-pointers

C opaque pointer gotchas


I'm working with a legacy C library interface (to C++) that exposes opaque pointers as

typedef void * OpaqueObject

In the library:

OpaqueObject CreateObject()
{
   return new OurCppLibrary::Object();
}

This of course provides absolutely no type safety for clients of this library. Should changing the typedef from a void pointer to structure pointer work exactly the same, but provide a small amount type safety?

typedef struct OpaqueObjectInternal_ *OpaqueObject 
// OpaqueObjectInternal_ is NEVER defined anywhere in client or library code

Are there any alignment issues or other gotchas that I have to worry about now that I am explicitly pointing to a structure, even though I'm really not pointing to one?


Solution

  • There are no gotcha's; that form is preferred exactly because of type safety.

    No, alignment is not an issue here. The pointer itself has a known alignment, and the alignment of the object it will point at is only of concern to the library implementation, not the user.