【问题标题】:std::make_unique with null pointer?std::make_unique 带有空指针?
【发布时间】:2019-07-11 16:31:21
【问题描述】:

如果我将空指针传递给std::make_unique,我无法找到任何文档。

是否抛出异常?

【问题讨论】:

  • 这个问题的根本原因是什么?为什么你认为将空指针传递给make_unique 会有一些不寻常或不寻常的事情?例如,传递空指针与传递有何不同。 42 或 "Hello World"?
  • make_unique 不采用指针并“使其唯一”,它创建(“制作”)具有唯一且可转让所有权的对象。 std::make_unique<int*>(nullptr) 使用这些属性创建一个空的 int*。
  • 显示代码,说明您真正询问的内容,因为坦率地说,问题本身没有意义。 std::make_unqiue<Type> 创建一个动态的 Type 实例并将所有权分配给随后返回的 std::unique_ptr<Type> 对象。这听起来像是您认为std::make_unique 做了其他事情,或者您将std::make_unique 与std::unique_ptr 的构造函数混淆了;他们是不同的野兽。

标签: c++ c++14 unique-ptr


【解决方案1】:

std::make_unique 将所有传递给匹配目标构造函数的参数转发。 因此,如果您传递nullptr,它将搜索接受 nullptr_t 的构造函数(或任何匹配的构造函数)。如果不存在,则编译失败。

class A
{
public:
   A(void*) { ... } // could also be A(int*) or template <typename T> A(T*)
};

...
std::make_unique<A>(nullptr); // constructs an A by calling A(void*), passing nullptr.

【讨论】:

  • 构造函数不需要声明 A(void *)。它可以是例如 A( int * );或 A( T *ptr, Args ...args );
【解决方案2】:

std::make_unique 旨在通过将参数转发给被包装对象的构造函数来构造一个被包装的对象。

按照您的意思将nullptr 传递给它没有任何意义。如果您需要清除std::unique_ptr 的内容,只需调用reset()。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 2015-02-04
    • 2013-06-30
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    相关资源
    最近更新 更多