代码之家  ›  专栏  ›  技术社区  ›  Mr.C64

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

  •  17
  • Mr.C64  · 技术社区  · 11 年前

    我尝试用VS2013编译一些C++代码 unique_ptr::reset() 似乎不适合 make_unique() ; 下面是一小段可编译的repro代码片段:

    #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 回复  |  直到 11 年前
        1
  •  24
  •   sehe    11 年前

    reset() 获取指针。

    你看起来想要的很简单 移动工作分配 :

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

    某些编译器可能仍然希望您指定 std::move() 但这不是严格要求的。

        2
  •  12
  •   juanchopanza    11 年前

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

    推荐文章