Вопрос

I tried compiling some C++ code with VS2013, and unique_ptr::reset() doesn't seem to work with make_unique(); a small compilable repro code snippet follows:

#include <memory>
using namespace std;

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

Compiling from command-line:

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

These are the errors from the MSVC compiler:

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 []
        ]

However, the following code seems to compile fine:

p = make_unique<int[]>(10);

What is the reason of this behavior? Why does unique_ptr::operator=() work with make_unique(), but unique_ptr::reset() doesn't?

Это было полезно?

Решение

reset() takes a pointer.

What you seem to want is simple move assignment:

#include <memory>
using namespace std;

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

some compilers might still like you to specify the std::move() there, but it's not strictly required.

Другие советы

Because std::unique_ptr::reset expects a pointer to an object to be managed, not another unique_ptr. make_unique creates a unique_ptr.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top