Reducing use of reinterpret_cast

39 views
Skip to first unread message

Erik Corry

unread,
Feb 21, 2025, 4:25:09 AM2/21/25
to v8-...@googlegroups.com
Reinterpret_cast is generally thought to be a code smell.

Reinterpret casts can cast absolutely anything to anything, and can introduce undefined behaviour.

In addition the intent is not clear.  Some uses of reinterpret_cast are for harmless things like signed or unsigned char.  Others are very tricky and warrant extra care and inspection when reading and code reviewing.

I propose to introduce some inlined casting functions that take care of the harmless cases. This should make the code easier to read, when we are used to them, and will make the tricky uses of reinterpret_cast stand out more.

Concretely:

char_cast
Only for casting uint8_t pointers to char pointers.  This is useful for using api's that take char pointers.

unsigned_cast
signed_cast
only for casting from an unsigned pointer to a signed pointer and the reverse. The types must be otherwise identical.

unvoid_cast<type>
Can cast only from void* to a real pointer. Useful for the return values from allocation routines.

A first example is at https://chromium-review.googlesource.com/c/v8/v8/+/6291127
This one implements char_cast, but calls it uint8_to_char_cast.  This is easier to read for the uninitiated, but uglier.

I have filed https://issues.chromium.org/issues/398125786 for discussion.

Reply all
Reply to author
Forward
0 new messages