A post on how to provide a pointer to a Qt Model/View or other APIs storing pointers to their data without using shared_ptr or unique_ptr for the actual object.
Providing a stable memory address
by Jens Weller
From the article:
Some APIs allow you to store a pointer to your data element. This is used to access additional information from your types to display them in Model/View Architecture.
A while ago I showed how you can implement a tree with shared_ptr and enable_shared_from_this and then display this in QTreeView. And when working on my current project I knew this problem would come around again. Maybe not for a tree and a tree view, but I'll clearly need to have some way to have ui panels display and edit my data classes and store a stable memory adress as a pointer in Qt models. Back in 2015 the Qt5 example still used a pointer allocated with raw new for this, in Qt6 the example uses unique_ptr. Using shared_ptr for this back in 2015 was a good decision, and the code works very well. For the moment I don't see that my current project would need to make use of enable_shared_from_this, so using unique_ptr would be a good option...
Add a Comment
Comments are closed.