February 13, 2012

maxvanceffer maxvanceffer
Lab Rat
50 posts

Custom object type and QList

 

Guys give some hint about operator overloading

I have such QList: QList<MyCustomType*> list;
What kind of operator==() , must have my custom type, to have ability use it in method QList::indexOf(MyCustomType*)

?

7 replies

February 13, 2012

Tobias Hunger Tobias Hunger
Mad Scientist
3224 posts

That should just work (as long as you are using pointers) without operator overloading.

February 13, 2012

Andre Andre
Area 51 Engineer
6076 posts

Indeed. Nothing needed. You are putting in pointers, and pointers already have the operators you need by default. Note that no comparisons will be made on the contents of the objects. It is purely a comparison of the pointer values.

 Signature 

Looking for Qt developers to join our team @ i-Optics: https://qt-project.org/forums/viewthread/25393/

February 14, 2012

maxvanceffer maxvanceffer
Lab Rat
50 posts

))) Just forgot to check if list is filled out. A on more question

QList<MyCustomType> list;
list.clear();

Is memory released, as objects goes out of scope ?

February 14, 2012

Andre Andre
Area 51 Engineer
6076 posts

Yes. However, you cannot do that with QObject derived types, as the types you put in your container must be copyable and default constructable. QObject does not meet those requirements. You can put pointer to a QObject in your container, but no delete will be called automatically on those pointers on destruction of the list object. That means that if that was the only pointer to object, you are leaking memory.

A last alternative is to store shared pointers in your list. QSharedPointer fulfils the requirements of types to put in a container, and when the list is destructed, they will automatically delete anything they pointed to if there are no other shared pointers pointing to the same data.

 Signature 

Looking for Qt developers to join our team @ i-Optics: https://qt-project.org/forums/viewthread/25393/

February 14, 2012

maxvanceffer maxvanceffer
Lab Rat
50 posts

Thx, but if containers contains of such clasess

  1. class MyClass : public QObject
  2. {
  3. ......
  4. };
  5.  
  6. QList<MyClass> list;
  7. list.clear();

?

Edit: please use @ tags around code sections; Andre

February 14, 2012

Andre Andre
Area 51 Engineer
6076 posts

That won’t compile. Line 6 will probably throw some rather complicated template-related error messages.

 Signature 

Looking for Qt developers to join our team @ i-Optics: https://qt-project.org/forums/viewthread/25393/

February 14, 2012

maxvanceffer maxvanceffer
Lab Rat
50 posts

Thx, big thx for advise))) !!!

 
  ‹‹ How to "signal" from a non-QObject?      [Solved] Customizing QTableWidget ››

You must log in to post a reply. Not a member yet? Register here!