N.A.
N.A.

Reputation: 1489

C++ type casting. When will static_cast succeed and reinterpret_cast will cause an issue?

I understand that a static_cast is a cast from one type to another that (intuitively) is a cast that could under some circumstance succeed and be meaningful in the absence of a dangerous cast. Meanwhile, a reinterpret_cast is a cast that represents an unsafe conversion that might reinterpret the bits of one value as the bits of another value.

Can someone describe a scenario when the code will compile, cast and static_cast will cause no issue, but with reinterpret_cast there will be an issue?

Upvotes: 24

Views: 2389

Answers (3)

Toby Speight
Toby Speight

Reputation: 30718

The simplest such case is reinterpret_cast<void*>(NULL), which may yield a non-null pointer.

By contrast, static_cast<void*>(NULL) is safe because it is required to yield a null pointer.

Why? NULL is an integer constant equal to 0. static_cast requires that 0 be converted to an appropriate null pointer, but reinterpret_cast does not have this same requirement. If the internal representation of a null pointer isn't the same as that of integer zero, then the results will be different. This type of breakage would be most likely on architectures with segmented addressing.

Upvotes: 17

Bathsheba
Bathsheba

Reputation: 234655

This will do it:

#include <iostream>
using namespace std;

struct C{int n;};
struct A{int n;};
struct B : A, C{};

int main()
{
    B b;
    B* pb = &b;
    cout << static_cast<C*>(pb) << "\n";
    cout << reinterpret_cast<C*>(pb);
}

Note the differences in the two addresses.

I've built some multiple inheritance here, and have put an explicit member in the base classes, in order to circumvent possible optimisation of empty base classes to size zero.

See https://ideone.com/QLvBku

Upvotes: 21

EmDroid
EmDroid

Reputation: 6066

One of such cases is multiple inheritance - static_cast does adjustment of the address (so the address of the base object pointer after the cast can be different from the derived object address, to point to the correct base class items).

reinterpret_cast does not do any address adjustments, so the cast to base class might use a wrong address (i.e. always returns the address of the derived object unchanged).

Upvotes: 9

Related Questions