[英]Looking at std::unique_ptr and its nullptr_t constructor
我試圖理解為什么unique_ptr
有一個nullptr_t構造函數
constexpr unique_ptr::unique_ptr( nullptr_t );
我假設這是因為正常的一個參數構造函數是顯式的,因此會拒絕nullptr值:
explicit unique_ptr::unique_ptr( pointer p );
但是當我構建一個例子時,編譯器很好:
namespace ThorsAnvil
{
template<typename T>
class SmartPointer
{
public:
SmartPointer() {}
explicit SmartPointer(T*){}
};
}
template<typename T>
using SP = ThorsAnvil::SmartPointer<T>;
int main()
{
SP<int> data1;
SP<int> data2(new int); // fine
SP<int> data3(nullptr); // fine
}
這是輸出:
> g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin14.0.0
Thread model: posix
> g++ -Wall -Wextra -std=c++11 SP1.cpp
為什么std :: unique_ptr需要額外的構造函數來獲取nullptr_t參數?
SP<int> data3(nullptr); // fine
您正在使用直接初始化,這會導致考慮explicit
構造函數。 嘗試以下操作,您的代碼將無法編譯
SP<int> data4 = nullptr;
現在添加以下構造函數,上面的行將編譯
SmartPointer(std::nullptr_t){}
因此, nullptr_t
構造函數使unique_ptr
在您想要將其初始化為nullptr
的情況下表現得像原始指針,但在其他可能實際為其指定原始指針的情況下避免任何意外的所有權轉移。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.