problemofficer
problemofficer

Reputation: 435

QT elements in vector initialization. How to solve private copy constructor problem?

I wanted to create a vector of a subclass of QGraphicsRectItem, named MyRect. This vector is initialized in MyClass:

MyClass::MyClass () : myVector_(80, std::vector<MyRect>(60, MyRect(true,true)))
...

I learned that vector constructs the first element and then copies it with the copy constructor. The problem is that QGraphicsRectItem's copy constructor is private and this doesn't work. (Very long error message, one hour of googling)

Now I have three possible solutions as I see it:

1.)Make a for-loop and populate myVector myself in the constructor body.

1b.) Just use regular array because it remains static anyway.

2.)Use MyRect* instead of MyRect as content of myVector (manual memory allocation -> bad)

3.)Use QVector that uses Object* by default and manages the memory for me.

After spending at least one hour on solving this I would like to hear from you if there are other good possibilities or what you think is the best solution. I am on the verge of dropping vectors for this and just using arrays.

Upvotes: 0

Views: 585

Answers (1)

J&#233;r&#244;me
J&#233;r&#244;me

Reputation: 27027

The vector, as you declared it, will have to manipulate instances of MyRect. This means that depending of what you do the with the elements of the vector, or if you copy the vector, the MyRect instances might be duplicated.

This is not possible, because that would mean creating a new item each time a copy occurs (this is why the QGraphicsItem constructor is private). You have to manipulate the items of your scene through a pointer.

Thus, to me the best solution is to store in your vector pointers on your items (your 2nd solution) :

std::vector<MyRect*>

Memory management shouldn't be a problem at all, as this will be handled by Qt : when you destroy the scene, all items part of this scene will be destroyed.

Your vector won't duplicate items (no instanciation), only pointers, which means you won't create new items you'd have to destroy yourself.

Upvotes: 2

Related Questions