Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Why cast to void* in this function?

16 views
Skip to first unread message

Ahmet Can ÜN

unread,
Nov 21, 2016, 1:54:36 PM11/21/16
to
Hi,

This function rests in fbstring.h header from facebook folly library.

Link: https://github.com/facebook/folly/blob/master/folly/FBString.h#L434

I didn't see why this code casts p back and forth to void*?
static RefCounted * fromData(Char * p) {
return static_cast<RefCounted*>(
static_cast<void*>(
static_cast<unsigned char*>(static_cast<void*>(p))
- sizeof(refCount_)));
}

Why can't it be written like this? Can anyone see a logical reason?

static RefCounted * fromData(Char * p) {
return static_cast<RefCounted*>(
static_cast<unsigned char*>(p)
- sizeof(refCount_));
}

Gareth Owen

unread,
Nov 21, 2016, 2:20:01 PM11/21/16
to
Ahmet Can ÜN <ahmet...@gmail.com> writes:

> Why can't it be written like this? Can anyone see a logical reason?
>
> static RefCounted * fromData(Char * p) {
> return static_cast<RefCounted*>(
> static_cast<unsigned char*>(p)
> - sizeof(refCount_));
> }

What did your compiler say?

Clue: Any pointer type can be static_cast to a void*,
and a void* can be static_cast to any pointer type, but ...

Ahmet Can ÜN

unread,
Nov 21, 2016, 2:51:30 PM11/21/16
to
Thank you. I'm still under the influence of C.

Öö Tiib

unread,
Nov 21, 2016, 2:55:02 PM11/21/16
to
Because static_cast is not meant for type punning between unrelated
types like that.

It is legal to use reinterpret_cast like that:

return reinterpret_cast<RefCounted*>(
reinterpret_cast<unsigned char*>(p)
- sizeof(refCount_));

It is legal to use C style cast like that:

return (RefCounted*)(
(unsigned char*)(p)
- sizeof(refCount_));


0 new messages