2016-06-07 46 views
0

當我嘗試編譯此代碼時,它失敗,說: 「錯誤:靜態斷言失敗:使用空函數指針刪除程序構造」。它所抱怨的是「return nullptr」。返回nullptr與我寫入的其他函數一起工作,返回unique_ptr。爲什麼這是如此不同,甚至無法編譯?使用自定義刪除程序返回uniqueptr的nullptr失敗

#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 testing\n"; 
    return 0; 
} 
+0

如果你想看到它運行:http://ideone.com/r0beTy – JadziaMD

回答

1

看樣子你需要使用一個函數對象,如:

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;,這反過來又在備註:

Remarks: If this constructor is instantiated with a pointer type or reference type for the template argument D, the program is ill-formed.

+0

的'如果(陣列)'檢查和'陣列= nullptr ;'聲明在這裏沒用。 – eepp