Archive 17/01/2023.

Does raw pointer createdChild from parent need to delete when changing new view?

Taymindis

Hi developers,

I’ve seen some example code there are created with raw pointer.
Doesn’t need to be deleted when change to new view?

Sample 1

Urho3D::Button* button = _uiRoot->CreateChild<Urho3D::Button>();

Sample 2

Text* windowTitle = new Text(context_);

Sample 3

URHO3D_HANDLER(SoundEffect, HandleSoundVolume);
KonstantTom

No, they don’t.
Sample 1: created button is child of _uiRoot (obviously) and stored in SharedPtr in _uiRoot (as any other child).

Sample 2: I think, there something like _uiRoot->AddChild (windowTitle); is exists below, so memory managment will be performed by parent element (as in Sample 1).

Sample 3: This macro is used for functions like this:

void SubscribeToEvent(Object* sender, StringHash eventType, EventHandler* handler);

So, Object (class, see Object.h) will perform memory managment in this case.

Taymindis

@KonstantTom

Nice! :slight_smile:

Thanks,

Eugene

If some function return raw pointer, you don’t have to do any memory management: the object is already stored somewhere internally. However, you may store the object in the SharedPtr if you don’t want it to be internally destroyed.

I don’t recommend to store Scene hierarchy objects (e.g. Components, Nodes and UIElements) in SharedPtr because it tampers lifetime of the objects and may end up with crashes during destruction.

It is always safe to store raw pointer in WeakPtr.