All Questions

141
votes
4answers
42844 views

Should I use static_cast or reinterpret_cast when casting a void* to whatever

Both static_cast and reinterpret_cast seem to work fine for casting void* to another pointer type. Is there a good reason to favor one over the other?
35
votes
3answers
4611 views

casting via void* instead of using reinterpret_cast

I'm reading a book and I found that reinterpret_cast should not be used directly, but rather casting to void* in combination with static_cast: T1 * p1=... void *pv=p1; T2 * p2= static_cast<T2*>...
3
votes
2answers
211 views

Why Doesn't reinterpret_cast Force copy_n for Casts between Same-Sized Types?

According to cppreference.com, reinterpret_cast: Converts between types by reinterpreting the underlying bit pattern. But wait, that's a lie cause it only works in these cases: When a pointe...
39
votes
7answers
6175 views

Why do we have reinterpret_cast in C++ when two chained static_cast can do its job?

Say I want to cast A* to char* and vice-versa, we have two choices (I mean, many of us think we've two choices, because both seems to work! Hence the confusion!): struct A { int age; char nam...
14
votes
1answers
1407 views

Does accessing the first field of a struct via a C cast violate strict aliasing?

Does this code violate strict aliasing? struct {int x;} a; *(int*)&a = 3 More abstractly, is it legal to cast between different types as long as the primitive read/write operations are type cor...
46
votes
9answers
26185 views

Why doesn't this reinterpret_cast compile?

I understand that reinterpret_cast is dangerous, I'm just doing this to test it. I have the following code: int x = 0; double y = reinterpret_cast<double>(x); When I try to compile the progra...
14
votes
3answers
771 views

Is casting std::pair<T1, T2> const& to std::pair<T1 const, T2> const& safe?

Is it safe (in theory or in practice) to reinterpret_cast a std::pair<T1, T2> const & into a std::pair<T1 const, T2> const &, assuming that the programmer hasn't intentionally done...
7
votes
6answers
794 views

C++ When should we prefer to use a two chained static_cast over reinterpret_cast

First of all, this is not a duplicate of Why do we have reinterpret_cast in C++ when two chained static_cast can do it's job?. I know situations where we cannot use even two chained static_cast to ac...
8
votes
7answers
4383 views

Equivalent of C++'s reinterpret_cast in C#

I wonder what's the equivalent of C++'s reinterpret_cast in C#!? Here's my sample: class Base { protected int counter = 0; } class Foo : Base { public int Counter { get { return...
5
votes
3answers
2302 views

reinterpret_cast

In the C++ Without Fear: A Beginner's Guide That Makes You Feel Smart book, and in chapter (8), it mentions the following about reinterpret_cast ....converts from one pointer type (int) to another (c...

Previous Next