Im creating a model in qt and came across this code:
class StringListModel : public QAbstractListModel
{
Q_OBJECT
public:
StringListModel(const QStringList &strings, QObject *parent = 0)
: QAbstractListModel(parent), stringList(strings) {}
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const;
private:
QStringList stringList;
};
Now I wonder, does this work? If a pass a qstringlist into this function thats localeted of the stack, and it runs out of scope, wont this object loose its stringlist?
Read both:
C++ reference in constructor
and:
Constructors accepting string reference. Bad idea?
.. where some people say that it will be invalid, but some say that the string (in their examples) will be copied to the local variable. This is really confusing.
If I understand what you’re asking, you’re concerned because the
QStringList &stringsis passed by reference?The initialization list calls the
stringList(const &QStringList)copy-constructor. This copy constructor copies the state of the passed&QStringListobject to a new object and assigns that object tostringListThis way even if the original&stringsgoes out of scope or is otherwise destroyed it won’t matter sincestringListpoints to a different object.In your second link there is no copy-constructor invoked… the member object is assigned to point at the same object that was passed to it. If the passed object is destroyed later in the program the member object would still be pointing to that destroyed object, making it invalid.