Question

I have a small question regarding casts.

Basically, I have the following code :

//Array of ALbyte, size is irrelevant
ALbyte buffer[1000];
//...
alcCaptureSamples(m_audioDevice,(ALCvoid*)buffer, sample);

and based on Scott Meyers Effective C++ advice, I'd like to use a c++-style cast for this.

But I don't really know which one I should pick between reinterpret_cast<ALCvoid*> and static_cast<ALCvoid*>. They say on MSDN that reinterpret_cast is used for converting a pointer to another pointer type.

But in Effective C++, I read

reinterpret_cast is intended for low-level casts that yield implementation-dependent (i.e. unportable) results, e.g., casting a pointer to an int

and that these should be very rare.

Then, which cast should I pick ? I obviously eliminated const_cast and dynamic_cast but can't determine which of the remaining I should use... (and this question didn't really help me as I don't know if the fact that I want to cast a fixed size array into a pointer types from OpenAL impacts or not).

Or should I completely avoid the C++-style cast in this case (but why) ?

Was it helpful?

Solution

In this case you probably don't need to do any casting.

Remember that arrays naturally decays to pointers, and that all pointers can be implicitly casted to void* (which I guess ALCvoid* is).

OTHER TIPS

You should use static_cast whenever possible as it performs compile-time checks: the compiler will not let you cast to an invalid pointer type.

reinterpret_cast cannot perform any compile time checks other than const to non-const. It's rarely used unless programming with older interfaces requiring void*.

Better still though is to design your code so you don't need to do casting: exploting polymorphism can help you avoid them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top