I am reading the book "an introduction to design patterns in c++ with qt". In chapter 6, (see the book link https://www.ics.com/designpatterns/book/containersofpointers.html), the author is trying to write a library class which is inherited from QList. In the example 6.35 where the addRefItem
function is defined. The author has very weird (at least for me) way to deal with the pointers.
void Library::addRefItem(RefItem*& refitem) {
here, the author used a pointer reference *&, he explained "so that null assignment after delete is possible". this is related to the last two lines, I assume.
QString isbn(refitem->getISBN());
RefItem* oldItem(findRefItem(isbn));
if(oldItem==0)
append(refitem);
else {
qDebug() << isbn << " Already in list:\n"
<< oldItem->toString()
<< "\nIncreasing number of copies "
<< "and deleting new pointer." ;
int newNum(oldItem->getNumberOfCopies() + refitem->getNumberOfCopies());
oldItem->setNumberOfCopies(newNum);
delete refitem;
refitem = 0;
}
}
I don't understand what the last two lines do. Why refitem
need to be deleted. It will be destructed anyway after the function return, right? and then why refitem
need to be assigned to be 0.
In the removeRefItem
function, there is also a similar line, delete ref
, see below. Can anyone help me understand all of these? A lot of thanks.
int Library::removeRefItem(QString isbn) {
RefItem* ref(findRefItem(isbn));
int numCopies(-1);
if(ref) {
numCopies = ref->getNumberOfCopies() - 1;
if(numCopies== 0) {
removeAll(ref);
delete ref;
}
else
ref->setNumberOfCopies(numCopies);
}
return numCopies;
}