I ran into a strange situation where casting to UBoxComponent requires additional steps before the object is properly recognized in a TMap:
UBoxComponent* HitBox1 = Cast<UBoxComponent>(HitResult.GetComponent());
if (HitBox1)
{
HitBox1->GetClass(); // Or HitBox1->GetName() also works
}
if (HitBox1 && HitboxMap.Contains(HitBox1))
{
// This evaluates to TRUE - map lookup succeeds after calling GetClass()
}
UBoxComponent* HitBox2 = Cast<UBoxComponent>(HitResult.GetComponent());
if (HitBox2 && HitboxMap.Contains(HitBox2))
{
// This evaluates to FALSE, even though it's the same object
// Map lookup fails without calling GetClass() or GetName() first
}
Is this behavior expected? Does UE’s casting system require accessing properties like GetClass() or GetName() to fully resolve/register the object before it can be properly identified in containers like TMap?
UBoxComponent* HitBox1 = Cast<UBoxComponent>(HitResult.GetComponent());
if (HitBox1)
{
HitBox1->GetClass(); // Or HitBox1->GetName() also works
}
if (HitBox1)
{
if (HitboxMap.Contains(HitBox1))
{
}
}
UBoxComponent* HitBox2 = Cast<UBoxComponent>(HitResult.GetComponent());
if (HitBox2)
{
if (HitboxMap.Contains(HitBox2))
{
}
}
You can also do cast wrapped in an if statement:
if (UBoxComponent* HitBox2 = Cast<UBoxComponent>(HitResult.GetComponent()))
{
if (HitboxMap.Contains(HitBox2))
{
}
}
This is important, imagine your cast HitBox2 fails, so in your if will check nullptr and return false, that’s great! So the second check gets called and may do some validations to the nullptr, and that’s where the problem comes in, since the TMap is going to do some checks and the pointer is a nullptr the validations will fail and raise an exception trying to read nullptr, etc.
With apologies to the original poster for not being able to answer the question, I’d like to clarify that C++ uses short-circuit evaluation, which means that if the first operand resolves the condition then the second one is never evaluated. In other words, the expression
bool Result = IsValid(Pointer) && Pointer->Function();
…is safe, because in the event when Pointer is invalid, we already know Result is false, so Function() will never be called.
I know about short circuit evaluate, but when it comes to unreal I’ve got Engine Crashes, with the EXCEPTION_ACCESS_VIOLATION reading address 0x000000000f, so after my last experience with UE 4.27 before release my last game I have started to check each pointer expresion separetaly and it solves my issue.
And the only conclusion that I’ve got was my previos comment. If I am making any mistake or some please let me know.