【发布时间】:2015-01-27 01:28:08
【问题描述】:
我试图理解为什么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。 -
nullptr_t构造函数也是explicit吗? -
@templatetypedef:不。只是 contexpr。
-
这将失败:
SP<int> data; data = nullptr; -
@CrappyExperienceBye 这可能就是你的答案——它允许直接分配
nullptr。这是一个充分的理由吗?
标签: c++ c++11 unique-ptr nullptr