Fortify doesn't like QListWidget::addItem(new QListWidgetItem)
and reports a false memory leak, even though QT manages the memory properly.
I'm trying to figure out a work-around.
I was told to use a std::shared_ptr
, but I haven't figured out the syntax yet.
Here's what I've got so far, but it reports an error about the type.
These 2 lines of code are all I need to fix, there is no further context. Just looking for the syntax for a shared pointer to QListWidgetItem
, adding the item to the list widget with addItem()
.
Any syntax that works is fine. MUST create a QListWidgetItem
and THEN add it. Cannot use additem("string") syntax.
In a header file, declare member variable item:
...
class Class1{
...
std::shared_ptr<QListWidgetItem> item;
...
};
In a source file:
...
Class1::ClassFunction1()
{
std::make_shared<QListWidgetItem> item("AStringToAdd");
ui->qlw->addItem(item);
}
CodePudding user response:
This might do the trick, based on code you show in your question:
class Class1{
...
std::unique_ptr<QListWidgetItem> item; // no need to use shared ptr
std::unique_ptr<...whatever you need here...> ui; // change ui to unique_ptr and put it after the item!
// remember to change construction of `ui` accordingly, and remove deleting it in destructor
...
};
Class1::ClassFunction1()
{
// reset member variable, don't create a new local variable
item.reset(new QListWidgetItem>("AStringToAdd"));
ui->qlw->addItem(item.get()); // pass naked pointer
}
That way, item
will go out of scope before ui
, and will be deleted by the unique_ptr
. When the item is deleted, it will notify the view, and view will remove the item.
If you do it the other way around, view will delete the item, but it has no way to notify the unique_ptr
. Therefore unique_ptr
will delete it again, resulting in Undefined Behavior, with luck just a crash.
CodePudding user response:
As per my comment you might be able to utilize std::unique_ptr
to silence fortify...
Class1::ClassFunction1 ()
{
auto item = std::make_unique<QListWidgetItem>("AStringToAdd");
/*
* Use std::unique_ptr::release() to transfer ownership of the
* QListWidgetItem to the QListWidget.
*/
ui->qlw->addItem(item.release());
}
The solution provided in the answer by @hyde is certainly the more robust. Having said that the original post is essentially seeking ways of trying to fix a problem with the fortify tool. So the real solution is "fix the tool" or find other, better analysis tools.