[英]Can't return nullptr for unique_ptr return type
我正在為SDL_Texture*
原始指針編寫一個包裝器,它返回一個unique_ptr
。
using TexturePtr = std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)>;
TexturePtr loadTexture(SDL_Renderer* renderer, const std::string &path) {
ImagePtr surface =
loadImage(path);
if (surface) {
return TexturePtr(
SDL_CreateTextureFromSurface(renderer, surface.get())
, SDL_DestroyTexture);
}
return nullptr;
}
但它給出了以下錯誤:
no suitable constructor exists to convert from "std::nullptr_t" to "std::unique_ptr<SDL_Texture, void (__cdecl *)(SDL_Texture *texture)>"
根據我的理解,傳遞nullptr代替unique_ptr是可以接受的。 我嘗試在最后一次返回時傳遞一個空的unique_ptr:
return TexturePtr();
但在構建期間遇到類似錯誤。
請讓我知道我在這里做錯了什么。
環境:編譯器:Visual C ++ 14.1
unique_ptr(nullptr_t)
構造函數要求刪除器是默認可構造的,並且它不是指針類型。 您的刪除器不滿足第二個條件,因為刪除器是指向函數的指針。 參見[unique.ptr.single.ctor] / 1和[unique.ptr.single.ctor] / 4 。
這種限制是一件好事,因為當您嘗試調用刪除器時,默認構造您的刪除器會導致nullptr
和未定義的行為,可能會導致段錯誤。
您可以將return語句更改為
return TexturePtr{nullptr, SDL_DestroyTexture}; // or just {nullptr, SDL_DestroyTexture}
或者,提供滿足上述要求的刪除器。 我在這里寫的另一個答案顯示了一個這樣的選擇。
編輯:其實我的下面的例子太簡單了,Pratorian關於刪除的暗示可能是你問題的線索。
您的期望是正確的,並且確實適用於GCC / Clang以及更新版本的msvc - 請參閱https://godbolt.org/z/CU4tn6以獲取編譯器輸出
#include <memory>
std::unique_ptr<int> f() {
return nullptr;
}
您可以嘗試不同的變化
#include <memory>
std::unique_ptr<int> f() {
return {};
}
但除此之外我想你別無選擇,只能升級你的編譯器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.