【问题标题】:Why doesn't make_unique work with unique_ptr::reset?为什么 make_unique 不能与 unique_ptr::reset 一起使用?
【发布时间】:2014-05-12 20:53:47
【问题描述】:

我尝试用VS2013编译一些C++代码,unique_ptr::reset()似乎不适用于make_unique();一个小的可编译重现代码 sn-p 如下:

#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() 不行?

【问题讨论】:

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


    【解决方案1】:

    reset() 接受一个指针。

    您似乎想要的是简单的移动分配

    #include <memory>
    using namespace std;
    
    int main() {
        unique_ptr<int[]> p = make_unique<int[]>(3);
        p = make_unique<int[]>(10);    
    }
    

    一些编译器可能仍然希望您在此处指定std::move(),但这不是严格要求。

    【讨论】:

      【解决方案2】:

      因为std::unique_ptr::reset 需要一个指向要管理的对象的指针,而不是另一个unique_ptrmake_unique 创建一个 unique_ptr

      【讨论】:

        猜你喜欢
        • 2017-03-03
        • 2023-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-10
        • 2018-07-29
        • 2018-03-09
        相关资源
        最近更新 更多