简体   繁体   English

c ++ unique_ptr移动构造函数

[英]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. 但是在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[]> . 已发布的C ++标准中的措辞表明, unique_ptr<T[]>不允许涉及const限定更改的转换。 This is a defect, DR 2118 , which was resolved by the changes in N4089 . 这是一个缺陷, DR 2118 ,由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). 较旧的编译器可能没有实现新规则(我为GCC 4.8实现了早期版本的修复,但GCC之前也不支持它)。

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: 直接release答案无法编译,因为Visual Studio将构造函数从另一个指针类型template<class _Ptr2> explicit unique_ptr(_Ptr2)private因此您必须这样做:

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. 但请务必添加注释,指出为什么简单的移动不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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