Using QSharedPointer with new[] yields “Mismatched free() / delete / delete[]” in valgrind

◇◆丶佛笑我妖孽 提交于 2020-01-20 08:14:25

问题


I have the following code:

QPair<QSharedPointer<unsigned int>, int> someclass::somefunction() {
    int siz = data_size();
    QSharedPointer<unsigned int> buffer(new unsigned int[siz]);

    // Fill the buffer...

    return qMakePair(buffer, siz);
}

At some point, the QSharedPointer returned by this function will go out of scope and the pointer set in the constructor will be free'd. Using valgrind 3.6.1, I get a "Mismatched free() / delete / delete[]" error. Is there anything wrong with my use of QSharedPointer or do I just have to live with this valgrind warning?


回答1:


One way to fix this is to write a custom deleter and pass that to the constructor of QSharedPointer like so:

template <typename T_>
void do_delete(T_ buf[])
{
    delete[] buf;
}

And then

QSharedPointer<unsigned int> buffer(new unsigned int[siz], do_delete<unsigned int>);

I am not sure whether there is a more elegant solution (which would be nice)



来源:https://stackoverflow.com/questions/7875764/using-qsharedpointer-with-new-yields-mismatched-free-delete-delete-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!