user1400047
user1400047

Reputation: 247

which conversion is right in C++?

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

Answers (5)

Skandh
Skandh

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

ecatmur
ecatmur

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 to T1” is converted to the type “pointer to cv T2”, the result is static_cast<cv T2*>(static_cast<cv void*>(v)) if both T1 and T2 are standard-layout types and the alignment requirements of T2 are no stricter than those of T1, or if either type is void.

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

SingerOfTheFall
SingerOfTheFall

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

James Kanze
James Kanze

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

Some programmer dude
Some programmer dude

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

Related Questions