为什么make_unique不能与unique_ptr::reset一起使用?

17

我尝试使用VS2013编译一些C++代码,但是unique_ptr::reset()似乎无法与make_unique()一起使用。下面是一个小的可编译复现代码片段:

#include <memory>
using namespace std;

int main() {
    unique_ptr<int[]> p = make_unique<int[]>(3);
    p.reset(make_unique<int[]>(10));    
}

使用命令行编译:

C:\Temp\CppTests>cl /EHsc /W4 /nologo test.cpp

以下是来自MSVC编译器的错误信息:

test.cpp(6) : error C2280: 'void std::unique_ptr<int [],std::default_delete<_Ty>
>::reset<std::unique_ptr<_Ty,std::default_delete<_Ty>>>(_Ptr2)' : attempting to
reference a deleted function
        with
        [
            _Ty=int []
,            _Ptr2=std::unique_ptr<int [],std::default_delete<int []>>
        ]
        C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\INCLUDE\memory(16
23) : see declaration of 'std::unique_ptr<int [],std::default_delete<_Ty>>::rese
t'
        with
        [
            _Ty=int []
        ]
然而,以下代码似乎可以成功编译:
p = make_unique<int[]>(10);

这种行为的原因是什么?为什么unique_ptr::operator=()可以与make_unique()一起使用,但unique_ptr::reset()不能呢?
2个回答

24

reset() 接受一个指针。

你似乎想要的是简单的移动赋值

#include <memory>
using namespace std;

int main() {
    unique_ptr<int[]> p = make_unique<int[]>(3);
    p = make_unique<int[]>(10);    
}

有些编译器可能仍然需要你在那里指定std::move(),但这并不是严格要求的。


12

由于 std::unique_ptr::reset 期望一个指向被管理的对象的指针,而不是另一个 unique_ptr。因此,make_unique 创建了一个 unique_ptr


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接