我試圖理解爲什麼unique_ptr
有nullptr_t構造看的std ::的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說法?
我的猜測,因爲它被宣佈爲'constexpr',因此被用於優化。 – Falmarri 2015-01-27 01:37:29
'nullptr_t'構造函數是否也是'explicit'? – templatetypedef 2015-01-27 01:38:11
@templatetypedef:不是。只是contexpr。 – 2015-01-27 01:38:46