Reputation: 219
When using a Qt container as Qlist, Qvector etc to hold some class (say a complex class with many data members and logics) and calling insert/append/push_back will the object added to the container be inserted to the container or it will be copied (cctor) ?
Suppose it is copied then If I dynamically allocate it and pass a pointer then only the pointer will be copied? And if I pass the object itself then I need to free the memory I've allocated before because the object is copied ?
I could some official documentation so I'm asking here...
Thanks
Upvotes: 2
Views: 810
Reputation: 49289
In the case of QObject
derived objects, you have to use dynamic allocation and just put pointers in the container, because such objects have unique identities and as such are prohibited from copying. In that case only the pointer is copied around, which is just an integer, the copying of which has no effect on the actual object it points to. With dynamically allocated objects you have to either manage lifetime manually or use Qt's parent/child functionality to have objects "collected" by their parent objects.
The values stored in the various containers can be of any assignable data type. To qualify, a type must provide a default constructor, a copy constructor, and an assignment operator. This covers most data types you are likely to want to store in a container, including basic types such as int and double, pointer types, and Qt data types such as QString, QDate, and QTime, but it doesn't cover QObject or any QObject subclass (QWidget, QDialog, QTimer, etc.). If you attempt to instantiate a QList, the compiler will complain that QWidget's copy constructor and assignment operators are disabled.
As the quoted text above indicates, when placing the actual instances in a container, copying of the object will occur. In this case you don't have to manually delete anything, since the source of the copy would typically be a local object and often a temporary, of which the compiler will take care.
"Placement new" is a C++ feature you can use to specify the place the object is constructed in memory, but it comes at complexity of managing it and some limitations. The advantages of placement new and memory pools rarely outweigh the increase of complexity and loss of flexibility.
Upvotes: 3