Reputation: 247
I want to covert a void* to char* reinterpret_cast and static_cast, which one is fit for ?static_cast<char*> or reinterpret_cast<char*>
Upvotes: 6
Views: 233
Reputation: 426
I guess it depends on context: static_cast<> should be used in case when there is implicit conversion. reinterpret_cast<> should be used when both pointers are of different types
Though reinterpret_cast is not recommended.
You shouldn't use static_cast for casting down an inheritance hierarchy, but rather dynamic_cast.
From http://msdn.microsoft.com/en-us/library/e0w9f63b(v=vs.80).aspx
The reinterpret_cast operator can be used for conversions such as char* to int*, or One_class* to Unrelated_class*, which are inherently unsafe.
Upvotes: -1
Reputation: 157354
reinterpret_cast
between pointer types is defined in terms of static_cast
through void *
:
5.2.10 Reinterpret cast [expr.reinterpret.cast]
7 - [...] When a prvalue
v
of type “pointer toT1
” is converted to the type “pointer to cvT2
”, the result isstatic_cast<cv T2*>(static_cast<cv void*>(v))
if bothT1
andT2
are standard-layout types and the alignment requirements ofT2
are no stricter than those ofT1
, or if either type isvoid
.
So if you're converting between standard-layout object pointer types (e.g. char *
) via void *
, then static_cast
is appropriate for the conversion to/from void *
.
Upvotes: 3
Reputation: 29966
reinterpret_cast
works for you in this case, but do not make a using it often a common practice, since it's the most dangerous cast. Basically, you can reinterpret_cast
totally unrelated pointers, so it's your obligation to take care of the result (i.e. checking if the result is valid for further usage).
Upvotes: 1
Reputation: 153919
It's largely a question of style. static_cast
can do any conversion
which is the opposite of an implicit conversion (and which doesn't
remove const
or volatile
). Since char*
to void*
is implicit,
static_cast
would seem indicated; the usual rule is to use
static_cast
in preference to reinterpret_cast
whenever possible.
Given that this use is particularly dangerous, some coding guidelines
might prefer reinterpret_cast
, to signal this fact.
Upvotes: 5
Reputation: 409176
static_cast
(together with dynamic_cast
) is for casting between objects in the same class hierarchy, while reinterpret_cast
is to cast between different types completely. So in your case you should go for reinterpret_cast
.
Upvotes: 3