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

标签 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 参数的额外构造函数?

最佳答案

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

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

SP<int>     data4 = nullptr;

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

SmartPointer(std::nullptr_t){}

因此,nullptr_t 构造函数使 unique_ptr 在您想将其初始化为 nullptr 的情况下表现得像原始指针,但避免在您实际上可能为其分配原始指针的其他情况下,任何令人惊讶的所有权转移。

关于c++ - 查看 std::unique_ptr 及其 nullptr_t 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28161751/

相关文章:

c++ - 如何给 child 一个指向 parent 的弱指针? (C++)

c++ - unique_ptr 和 shared_ptr 的区别

c++ - std::set 中的 unique_ptr 无法找到 operator< 即使它在那里

C++何时调用字符串析构函数

c++ - 如何使用 SFINAE 选择最接近的匹配类型特征?

c++ - 使用 std::enable_if 的正确方法

c++ - C++ 编译器如何区分二元运算符和模板的标记 >>

c++ - 从模拟数据构建非常大的马尔可夫链的最佳/最快方法是什么?

c++ - 为什么在两个不同的类中调用 TinyXPath 时,同一对象会给出不同的结果?

c++ - 为什么 boost filter_iterator 有奇怪的 make_filter_iterator 函数?