It's rather not a question "how to do it" it's rather "how to do it the right way"
I'm developing an editor in Qt where different widgets display the children and its (member) variables. Each of these widgets should hold a reference/pointer to the edited child to display and change their member variables.
The first attempt was the old ANSI C way I learned (and still kinda stuck in) with simple raw pointer to the used objects. It works fine but since the C++11 standard supports smart pointer and using them is recommended I'm trying to use them.
The problem is, I'm not quite sure what's the "best way" to use them in this case... After reading Smart Pointers: Or who owns you baby? and Which kind of pointer do I use when? and a few others I came to different conclusions:
The first is to use a*unique_ptr
since the edited object is clearly the owner which creates and also deletes its children. The widgets are simply referring to the child to show or change them.
The problem is how should the widgets refer to the child...
for now I'm simply still using a raw pointer I got with the get()
method of the unique_ptr
but this seems kinda flawed to me.
I still can accidentaly call delete on the pointer and cancel the benefits of the smart pointer.
The second approach is to use a shared_ptr
because many objects refer to the child and edit it. Also accidentaly deleting it in one widget would do no harm because it is still owned by other objects.
The problem is they own it. When I want to delete it from the edited object I also have to signal all widgets to delete it before it is really gone. (this again seems flawed and error-prone)
I'm not really content with both ways. Is there a clean(er) way to point to the unique_ptr
child of the object? Or am I missing a completely different and better approach to this problem?