简体   繁体   中英

Understanding stack when passing object to param

I'm new with C++, trying to understand some stack issues.

In the code bellow, list is created in the stack, right? So each string item is stored in a stack position (its address). Now, when I pass list in the reference param of QStringListModel(const QStringList &strings, ...) the list is not copied, but just a reference(addr) is passed in, right? So it remains in the same stack scope of the method? If list really resides in the stack how it is not destroyed when its scope finish? If it remains, as soon I add new items to list, inside the model, will the stack grow/shrink?

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    // ...

    QStringList list;
    list << "aaa" << "bbb" << "ccc";
    QStringListModel *model = new QStringListModel(list, this);

    // ...
}

Yes, list is valid until the MainWindow constructor returns. It is also correct that QStringListModel does not receive a copy of the list.

QStringListModel can only inspect the list inside the constructor call, if it wants to keep some information, it has to make its own copy.

This is not guaranteed nor enforced by the compiler, but it is common practice. A function that stores a reference, or completely takes ownership of an object, should always be documented to do that, exactly because of the reason you have just found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM