Why does make_unique not work with unique_ptr :: reset?

I tried to compile C ++ code with VS2013, but unique_ptr::reset()it does not seem to work with make_unique(); the following small snippet of code snippet:

#include <memory>
using namespace std;

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

Compilation from the command line:

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

These are the MSVC compiler errors:

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 for this behavior? Why unique_ptr::operator=()does it work with make_unique(), but unique_ptr::reset()does not work?

+4
source share
2 answers

reset() takes a pointer.

It seems you need a simple transfer destination:

#include <memory>
using namespace std;

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

some compilers still like to point std::move()there, but this is not strictly required.

+13
source

std::unique_ptr::reset , , unique_ptr. make_unique unique_ptr.

+6

Source: https://habr.com/ru/post/1534535/


All Articles