Search code examples
c++qtqlist

QList filled in constructor but accessed in other function


I'm not very sure about this C++ code.

#include <QList>
#include <QString>

using namespace std;

class MyClass {
    public:
            QList<QString> m_List;

    MyClass() {
            QString text1("foo1");
            m_List << text1;

            QString text2("foo2");
            m_List << text2;
    }

};

int main() {
    MyClass myClass;
    for (int i = 0; i < myClass.m_List.size(); ++i) {
            cout << myClass.m_List.at(i).toStdString()  << endl;
    }
}

I don't understand why it's work because I create and add QString in my QList in the constructor.
So, my instance text1 shouldn't exist anymore at the end of constructor and when I access to QList element in the loop this shouldn't work, but the output look nice :

foo1
foo2

cppcheck don't say anything about this code.
This code is it correct ?


Solution

  • Your code is correct.

    Yes, the local instances do not exist anymore. But that does not matter. QList stores data by value. What ever you pass to a QList is copied and the copy is stored in the list. So even if your local QString objects where discarded when leaving the constructor, the copies in QList still exist.