user3713179
user3713179

Reputation: 361

QList takeLast() and removeLast() conflict

When I try to run this code:

QStringList foo;
foo << "bar";
QString last;
last = foo.takeLast();
qDebug() << last;
foo.removeLast();

The IDE raises this error:

ASSERT: “!isEmpty()” in file ......\Qt\Qt5.3.0\5.3\mingw482_32\include/QtCore/qlist.h, line 299

If I disable the line with removeLast() command by toggling comment the code works fine. I do not understand this behavior since takeLast() runs when foo is not yet an empty list (removeLast() is called successively). Is a bug? is there a way to save the last before QStringList is emptied?

Upvotes: 0

Views: 2906

Answers (2)

Яois
Яois

Reputation: 3858

QList::takeLast() removes the last element from the list, as explain in the documentation.

Use QList::last() instead (or, equivalently, QList::back()).

Upvotes: 3

BartoszKP
BartoszKP

Reputation: 35891

It's a quite common convention in such APIs, that the word "take" is ought to be taken literally - this function really takes away the last element, i.e. removes it, and returns it. You can read about it in the documentation:

Removes the last item in the list and returns it.

You can use last() to obtain the last element without removing it. This is also Qt's prevailing convention that getters are named without the word "get" - just the name of the thing they're "getting".

Upvotes: 3

Related Questions