Reputation: 99
Is this a good practice to store graphic items of scene in lists?
I know that QGraphicsItem
has virtual method int type()
and you can dynamically find items by type. So what I mean is that I want to store my graphic items on stack in separate lists.
class Scene : public QGraphicsScene
{
public:
// Constructors etc.
private:
// Store graphic items in lists by value
QList<Carrot> m_carrots;
QList<Apple> m_apples;
};
This might sound dumb but the main concerns I have that in my current project everything is bound on using pointers and sometimes there are segmentation faults. And deleting items using
delete item;
item = nullptr;
And I want to manage items just using let's say m_apples.removeAt(index).
The problem is I don't know yet what it can lead to, also the project is pretty huge, so these changes can affect other pieces of code and take a lot of time. But I think it might help in managing memory safer way.
Thanks in advance
Upvotes: 0
Views: 353
Reputation: 98505
If you store items by value, you must treat them as values and let the container manage the memory. An explicit delete
on such an item is a bug. Qt's item classes are not copyable - thus you can:
Make the derived classes copyable as QList
has to copy.
Use std::list
as it doesn't need to copy.
Use a vector of unique pointers, e.g. std::vector<std::unique_ptr>
.
Upvotes: 0