Search code examples
c++qtmemory-managementdestructorqmap

C++ variables don't get deleted at the end of the scope


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?


Solution

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