0

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) ?

JBL
  • 12,588
  • 4
  • 53
  • 84
  • 1
    Maybe [this SO question/answers](http://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-and-reinterpret-cast-be-used) can help you. – dyp Jun 19 '13 at 13:40

2 Answers2

3

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).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    This might be a bit nit-picky, but wouldn't it be clearer to say "implicitly converted" (if you don't need to do any [*casting*](http://stackoverflow.com/questions/1374325/is-there-any-difference-between-type-casting-type-conversion)). +1 nevertheless – dyp Jun 19 '13 at 13:47
  • Indeed... I don't know why but I thought that it feels wrong not to make the cast (or rather "conversion") explicit (as it was to `ACLvoid*` and not to pure `void*`)... – JBL Jun 19 '13 at 13:53
0

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Well in this case I think I can't really avoid that and redesign (though I'd like to), because of the types OpenAL requests in its functions... – JBL Jun 19 '13 at 13:44