Fabricio
Fabricio

Reputation: 7935

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);

    // ...
}

Upvotes: 1

Views: 63

Answers (1)

alain
alain

Reputation: 12057

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.

Upvotes: 1

Related Questions