简体   繁体   中英

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

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM