mercredi 4 avril 2018

Qt: How to use Qt's Smartpointers

I have experience in "old-fashioned" C++ programming (i.e. I care myself about pointers and memory management). I do want to make use of modern concepts though.

Since my application makes heavy use of Qt, I'd like to use Qt's smartpointers. I am however somewhat confused about smartpointers in general, and their use in Qt.

1.) As far as I understand, if I derive from QObject, I should better stick to Qt's object tree and ownership model and forget about smartpointers. Correct?

2.) In C++ I can get by with std::shared_ptr and std::unique_ptr. What are the equivalent smart pointers in Qt?

Suppose I have the following code:

QList<MyObject *> * foobar(MyOtherObject *ptr) {

   // do some stuff with MyOtherObject

   QList<MyObject* > ls = new QList<MyObject*>();
   for(int i=0;i<10;i++) {    
       MyObject* mi = new MyObject();
       ...
       ls.insert(mi);
   }
   return ls;
}

int main() {

   MyOtherObject* foo = new MyOtherObject();
   QList<MyObject*> *bar = foobar(foo);
  // do stuff
  // and don't care about cleaning up?!
}

3.) How to translate the above snippet into a version using smartpointers?

4.) In particular: Should I change function signature into using smartpointers? It seems to create quite complex type signatures (return type and passed arguments). Also what if some "legacy" function calls another function - is it better to write function signatures with raw pointers, and use smartpointers only "inside" functions?

5.) What smartpointer should replace ls in the function foobar? What is the pointer type that should be used for mi, i.e. the objects stored in the QList?

Aucun commentaire:

Enregistrer un commentaire