我正在尝试理解为什么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参数?
nullptr_t
构造函数也是explicit
的吗? - templatetypedefSP<int> data; data = nullptr;
- Bill Lynchnullptr
。这是否足够证明了它的正当性? - templatetypedef