First of all, it seems odd that you'd need to cast an unsigned char pointer to a class pointer. I'd ask myself why. Maybe the bar method should be a method on a factory class that returns a pointer to a base class. But, assuming the bar function can't be rewritten and you really do need to cast its return value into a pointer to a Foo object, I'd write the code this way:
Foo* foo = reinterpret_cast<Foo*>(bar());
I'd maybe add a comment explaining why this unusual cast is necessary. Another thing to consider -- who manages the memory returned by bar? I've seen many a memory leak over the years, so I'm always looking out for them.
1 comment:
First of all, it seems odd that you'd need to cast an unsigned char pointer to a class pointer. I'd ask myself why. Maybe the bar method should be a method on a factory class that returns a pointer to a base class. But, assuming the bar function can't be rewritten and you really do need to cast its return value into a pointer to a Foo object, I'd write the code this way:
Foo* foo = reinterpret_cast<Foo*>(bar());
I'd maybe add a comment explaining why this unusual cast is necessary. Another thing to consider -- who manages the memory returned by bar? I've seen many a memory leak over the years, so I'm always looking out for them.
Post a Comment