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

Looking at std::unique_ptr and its nullptr_t constructor

本文关键字:nullptr 构造函数 及其 ptr unique 查看 std      更新时间:2023-10-16

我试图理解为什么unique_ptr有一个nullptr_t构造函数

constexpr unique_ptr::unique_ptr( nullptr_t );

我假设这是因为正常的 one 参数构造函数是显式的,因此会拒绝 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的情况下表现得像原始指针,但在您可能实际为其分配原始指针的其他情况下避免任何令人惊讶的所有权转移。