查看std :: unique_ptr及其nullptr_t构造函数

时间:2015-01-27 01:28:08

标签: c++ c++11 unique-ptr nullptr

我试图理解为什么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参数?

1 个答案:

答案 0 :(得分:6)

SP<int>     data3(nullptr);  // fine

您正在使用直接初始化,这会导致考虑explicit构造函数。请尝试以下操作,您的代码将无法编译

SP<int>     data4 = nullptr;

现在添加以下构造函数,上面的行将编译

SmartPointer(std::nullptr_t){}

因此,nullptr_t构造函数使unique_ptr行为类似于原始指针,如果您要将其初始化为nullptr,但在其他情况下避免任何意外的所有权转移你实际上可能正在为它指定一个原始指针。

相关问题