使用自定义删除程序返回unique_ptr的 nullptr 失败



当我尝试编译此代码时,它失败了:" 错误:静态断言失败:使用 NULL 函数指针删除器构造"。它抱怨的行是"返回nullptr"。返回 nullptr 适用于我编写的其他返回unique_ptr的函数。为什么这如此不同,甚至无法编译?

#include <iostream>
#include <memory>
template<typename ArrayType>
void deleter(ArrayType* array) noexcept
{
    if (array)
    {
        delete[] array;
        array = nullptr;
        std::cout << "Freed array." << std::endl;
    }
}
template<typename ArrayType>
std::unique_ptr<ArrayType[], decltype(&deleter<ArrayType>)> makeArray(const std::size_t size)
{
    return std::unique_ptr<ArrayType[], decltype(&deleter<ArrayType>)>{
        new ArrayType[size],
        deleter<ArrayType>
    };
}
std::unique_ptr<int[], decltype(&deleter<int>)> createInt(int s)
{
    if (s == 3)
        return makeArray<int>(3);
    else
        return nullptr;
}
void testArr(int arr[])
{
    if (arr != nullptr)
    {
        arr[0] = 1;
        arr[1] = 2;
        arr[2] = 3;
        std::cout << "Value 2 is " << arr[1] << std::endl;
    }
    else
        std::cout << "Array is empty." << std::endl;
}
int main() {
    auto arr0{createInt(4)}, arr1{createInt(3)};
    std::cout << "tTesting arr0:n";
    testArr(arr0.get());
    std::cout << "tTesting arr1:n";
    testArr(arr1.get());
    std::cout << "tFinished testingn";
    return 0;
}

看来你需要使用一个函数对象,比如:

template<typename ArrayType>
struct deleter {
    void operator()(ArrayType* array) {
    if (array)
    {
        delete[] array;
        array = nullptr;
        std::cout << "Freed array." << std::endl;
    }
    }
};

请参阅此处示例:

http://coliru.stacked-crooked.com/a/172693cdc5704531

我认为标准中的相关部分在 20.8.1.2.1 [unique.ptr.single.ctor] 中。

返回 nullptr 你调用 : unique_ptr& operator=(nullptr_t) noexcept; 调用 constexpr unique_ptr() noexcept; ,而 又有 备注:

备注: 如果此构造函数是使用指针类型或 模板参数 D 的引用类型,则程序格式不正确。

最新更新