unique_ptr可以采用nullptr值吗?

时间:2021-07-12 21:13:44

Is this code fragment valid? :

这段代码片段有效吗? :

unique_ptr<A> p( new A());
p = nullptr;

That is, can I assign nullptrto a unique_ptr ? or it will fail?

也就是说,我可以指定nullptrto一个unique_ptr吗?还是会失败?

I tried this with the g++ compiler and it worked, but what about other compilers?

我用g ++编译器尝试了这个并且它有效,但是其他编译器呢?

1 个解决方案

#1


28  

It will work.

它会工作。

From Paragraphs 20.7.1.2.3/8-9 of the C++11 Standard about the unique_ptr<> class template:

从C ++ 11标准的第20.7.1.2.3 / 8-9段开始,关于unique_ptr <>类模板:

unique_ptr& operator=(nullptr_t) noexcept;

unique_ptr&operator =(nullptr_t)noexcept;

Effects: reset().

Postcondition: get() == nullptr

后置条件:get()== nullptr

This means that the definition of class template unique_ptr<> includes an overload of operator = that accepts a value of type nullptr_t (such as nullptr) as its right hand side; the paragraph also specifies that assigning nullptr to a unique_ptr is equivalent to resetting the unique_ptr.

这意味着类模板unique_ptr <>的定义包括operator =的重载,它接受类型为nullptr_t的值(例如nullptr)作为其右侧;该段还指定将nullptr分配给unique_ptr等同于重置unique_ptr。

Thus, after this assignment, your A object will be destroyed.

因此,在此赋值之后,您的A对象将被销毁。

#1


28  

It will work.

它会工作。

From Paragraphs 20.7.1.2.3/8-9 of the C++11 Standard about the unique_ptr<> class template:

从C ++ 11标准的第20.7.1.2.3 / 8-9段开始,关于unique_ptr <>类模板:

unique_ptr& operator=(nullptr_t) noexcept;

unique_ptr&operator =(nullptr_t)noexcept;

Effects: reset().

Postcondition: get() == nullptr

后置条件:get()== nullptr

This means that the definition of class template unique_ptr<> includes an overload of operator = that accepts a value of type nullptr_t (such as nullptr) as its right hand side; the paragraph also specifies that assigning nullptr to a unique_ptr is equivalent to resetting the unique_ptr.

这意味着类模板unique_ptr <>的定义包括operator =的重载,它接受类型为nullptr_t的值(例如nullptr)作为其右侧;该段还指定将nullptr分配给unique_ptr等同于重置unique_ptr。

Thus, after this assignment, your A object will be destroyed.

因此,在此赋值之后,您的A对象将被销毁。