what does this C code snippet do?
IEntity* wLocalEntity= const_cast<IEntity*>(BaseSimSystem::getEntityRef());
if(wLocalEntity!=0){
mEntitySpeed=wLocalEntity->getSpeed();
}
I'm not sure how it's related to a template creation. Can someone explain to me what this code does? Thank you.
CodePudding user response:
Here's the code.
IEntity* wLocalEntity= const_cast<IEntity*>(BaseSimSystem::getEntityRef());
if(wLocalEntity!=0){
mEntitySpeed=wLocalEntity->getSpeed();
}
If you actually get asked about this code, the first thing I'd do is complain about the if-clause. that 0 should be nullptr as so:
if (wLocalEntity != nullptr) {
mEntitySpeed = wLocalEntity->getSpeed();
}
Also, please tell me you know you shouldn't compress your code so tightly. Bugs hide when you shove all those operators together with no whitespace.
Now, let's look at line 1:
IEntity* wLocalEntity = const_cast<IEntity*>(BaseSimSystem::getEntityRef());
Clearly, wLocalEntity is a pointer to an IEntity. I hope you understood that.
The const_cast<>
bit is ridiculous and possibly a bug. We don't know what BaseSimSystem::getEntityRef() returns, but I suspect it returns a const pointer, and now you're trying to assign that back to a non-const variable. The const_cast<> is getting rid of the constness.
The correct code is almost certainly:
const IEntity * wLocalEntity = BaseSimSystem::getEntityRef();
However, it's possible that IEntity has methods that aren't flag const that really should be, so you might have to do this because some other programmer didn't apply const when he should have.
So the const_cast<IEntity *>
says "take the return value in those parenthesis and yes, I know they're not a non-const IEntity *, but don't warn me about it because supposedly I know what I'm doing.
How's that?