Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting pointer to object to void * in C++

I've been reading StackOverflow too much and started doubting all the code I've ever written, I keep thinking "Is that undefined behavour?" even in code that has been working for ages.

So my question - Is it safe and well defined behavour to cast a pointer to an object (In this case abstract interface classes) to a void* and then later on cast them back to the original class and call method using them?

I'm fully aware that the code that does this is probably awful. I wouldn't even consider writing it like this now (this is old code which I don't really want to change), so I'm not looking for a discussion of better ways to do this. I already know how to write it better if I ever did this again. But if it's actually broken to rely on this in C++ then I'll have to look at changing the code, if it's merely awful code then changing it won't be a priority.

I would have had no doubts about something this simple a year or two ago but as my understanding of C++ increases I actually find I have more and more worries about code being safe under the standards even if it works perfectly well. Perhaps reading too much stack overflow is a bad thing for productivity sometimes :P

like image 772
jcoder Avatar asked Apr 10 '10 12:04

jcoder


2 Answers

You are safe.

From C++(0x) draft,

§5.2.9/13 (for static_cast):

A value of type pointer to object converted to “pointer to cv void” and back, possibly with different cv-qualification, shall have its original value.

§5.2.10/7 (for reinterpret_cast):

Converting an rvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value.

(Of course, casting to an unrelated class is undefined behavior.)

like image 109
kennytm Avatar answered Sep 23 '22 12:09

kennytm


So my question - Is it safe and well defined behavour to cast a pointer to an object (In this case abstract interface classes) to a void* and then later on cast them back to the original class and call method using them?

Yes – as long as you cast back to the exact same type. Otherwise, base class pointer adjustments may destroy the value of the pointer.

In practice, this is (probably) only relevant when using multiple inheritance: pointers to a derived class may differ in their physical address from pointers to their base class.

like image 30
Konrad Rudolph Avatar answered Sep 21 '22 12:09

Konrad Rudolph