سؤال

I have the following code snippet (which basically discoveres a given folder recursively) and I don't understand something about memory management in C++:

for(QFileInfo child : root.entryInfoList()) {
    if (child.isDir() &&
            child.absoluteFilePath() != rootInfo.absoluteFilePath() &&
            child.absoluteFilePath() != rootInfo.absolutePath())
    {
        discoverDirectory(child.absoluteFilePath());
    } else if (child.isFile()) {
        qDebug() << "Visiting file: " + child.absoluteFilePath();

        watchDog->addPath(child.absoluteFilePath());
        fileSysEntries.insert(child.absoluteFilePath(), child);
    }
}

As I remember, variables created without new are disposed of at the end of the scope, so whatever is in the entryInfoList it's going to be disposed of at the end of this function. So I thought this shouldn't work since I want to store the child items in the fileSysEntries QMap but they will be deleted after this call. However, I can access them later for some reason. I thought this is because the child's copy constructor is called when inserting it into the fileSysEntries map but the insert function has the following signature:

iterator QMap::insert(const Key & key, const T & value)

where value is a call by name parameter, so the child items don't get copied I guess, which confuses me a little bit. Could someone show me what I miss?

هل كانت مفيدة؟

المحلول

The value is passed to the QMap by reference (no copy here) and afterwards copied inside the map.

نصائح أخرى

There are two copies being performed :

  • for(QFileInfo child : root.entryInfoList()) - will create a copy of every object f rom the list.
  • fileSysEntries.insert(child.absoluteFilePath(), child); - will also create a copy when inserting into a QMap.

Well, the fact the insert (or insertMulti) function takes the value to be inserted by reference doesn't prevent it from making a copy afterwards.

And when you look at the Qt source code (qmap.h), it's actually what's happening:

template <class Key, class T>
Q_INLINE_TEMPLATE typename QMap<Key, T>::iterator 
QMap<Key, T>::insert(const Key &akey, const T &avalue)
{
    //Stuff
    last->value = avalue;//Here, a copy is made through copy assignement
    //Stuff
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top