QSharedPointer ::创建()

时间:2014-01-08 03:52:10

标签: c++ qt pointers qt5 qsharedpointer

在Qt 4中,我有以下数组:

QSharedPointer<unsigned char> encrypted(new unsigned char[RSA_size(publickey)]);

如何将两个分配合并为一个新的Qt 5创建函数?

QSharedPointer<T> QSharedPointer::create()

1 个答案:

答案 0 :(得分:4)

你的第一个例子是错的,不仅会泄漏内存,还会导致UB。定义QSharedPointer<unsigned char>时,您要为单个元素定义智能指针,而不是元素数组,因此将调用delete,而不是delete[]

将其更改为:

QSharedPointer<unsigned char> encrypted(new unsigned char[RSA_size(publickey)], [](unsigned char* x){ delete[] x; });

即:您必须为指针提供自定义删除器。

最后,QSharedPointer::create函数应该只用于一个元素,而不是元素数组,它可以用于:

auto x = QSharedPointer<unsigned char>::create();