简体   繁体   中英

c++ unique_ptr move constructor

In another post was mentioned this doesn't work due to the different deleter types.

std::unique_ptr<char[]> ptr(nullptr);
std::unique_ptr<const char[]> ptr_2(std::move(ptr));

But there was no solution to achieve this behavior in VSS2013. Does somebody know a short and clean solution?

Edit::

std::unique_ptr<const char[]> ptr_2(ptr.release());

doesn't work and compiles with the error:

error C2280: 'std::unique_ptr<const char [],std::default_delete<_Ty>>::unique_ptr<char*>(_Ptr2)' : attempting to reference a deleted function
1>          with
1>          [
1>              _Ty=const char []
1>  ,            _Ptr2=char *
1>          ]
1>          C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\memory(1612) : see declaration of 'std::unique_ptr<const char [],std::default_delete<_Ty>>::unique_ptr'
1>          with
1>          [
1>              _Ty=const char []
1>          ]

The wording in the published C++ standard says that conversions involving changes in const-qualification are not allowed for unique_ptr<T[]> . This is a defect, DR 2118 , which was resolved by the changes in N4089 .

Older compilers may not implement the new rules (I implemented an earlier version of the fix for GCC 4.8, but GCC didn't support it before then either).

The straightforward release answer does not compile since Visual Studio defines constructor from another pointer type template<class _Ptr2> explicit unique_ptr(_Ptr2) as private so you must do it like this:

std::unique_ptr<const char[]> ptr_2(const_cast<const char*>(ptr.release()));

to make the pointer types match.

Sure, simply avoid the move and do it manually:

std::unique_ptr<char[]> ptr(nullptr);
std::unique_ptr<const char[]> ptr_2(ptr.release());

You can always release:

std::unique_ptr<const char[]> ptr_2(ptr.release());

But be sure to add a comment pointing out why a simple move doesn't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM