Timers, Lifespan and References?

Hi,

General question to a problem in c++
Its about two objects which need each other but have different lifespans.

Player and Effect with lifespan

The effect has a lifespan and gets destroyed after a few seconds. When it gets
destroyed it revokes the effect that it had on the player. For this reason i keep a pointer to the player as member variable in the effect class. But what is when the player might die?

Check pointer to be nullptr?

i could check if the pointer to the player is a nullptr. Maybe the effect lasts 5 minutes. The player is already dead after a few seconds. Will the pointer be nullptr? Could it happen, that the address the pointer is pointing to got allocated by some other stuff in the time?

Solution 1: Everything belongs to the player?

Keep effect inside the player. Same problem. When effect gets destroyed the pointer points nowhere.

TArray<AEffect*> EffectsOnPlayer

This would work but as i spawn an Actor like Effect (Actor because it should be displayed in the HUD) i only get a pointer from world->spawnactor(…).

TArray<AEffect> EffectsOnPlayer

Solution 2: Events?

Events like in java ( i don’t know events in c++ ) to register the death of the player and also destroy the effect.
since the player is dead already.

Solution 3: Iterate through available AActors

This dosn’t look elegant to me. But my intention says i should use this.
Actually this is from:
https://wiki.unrealengine.com/Iterators:Object%26_Actor_Iterators,_Optional_Class_Scope_For_Faster_Search Thx to RAMA

void AYourControllerClass::PrintAllEffectActorLocations()
{
	//EngineUtils.h
	for (TActorIterator<AEffect> ActorItr(GetWorld()); ActorItr; ++ActorItr)
	{
		ClientMessage(ActorItr->GetName());
		ClientMessage(ActorItr->GetActorLocation().ToString());
	}
}

Could somebody light up the darkness :slight_smile:

No Events, No iteration through all AActors. puh good :slight_smile:
There are two things which work to check if a pointer to some object is valid.

if (m_ball->IsValidLowLevel())

and

if (!m_ball->IsPendingKill())

But can someone explain the difference?

It works but can it happen, that the space the pointer points to, gets allocated by a new ball (same memory) and the two functions are valid again but they shouldn’t because its a different ball?