简体   繁体   English

删除带有自定义删除的unique_ptr构造函数

[英]unique_ptr constructor with custom deleter is deleted

This example compiles and runs well with gcc 4.8.3: 这个例子用gcc 4.8.3编译并运行良好:

#include <memory>
#include <functional>
#include <iostream>

int main() {
    auto str = new const char[6]{'h', 'e', 'l', 'l', 'o', '\0'};
    std::unique_ptr<const char[], std::function<void(const char *)>> u_ptr(str, [](const char *s){ delete[] s; });
    std::cout << u_ptr.get() << std::endl;
}

But when I try it with Visual Studio Professional 2013 it doesn't compile (complains about a deleted function). 但是,当我尝试使用Visual Studio Professional 2013时,它无法编译(抱怨已删除的功能)。 Is this not yet possible with Visual Studio 2013? Visual Studio 2013还没有这个功能吗? Or is my sample code wrong and gcc ignores my mistake? 或者我的示例代码是错误的,gcc忽略了我的错误?

Error is: 错误是:

main.cpp(8) : error C2280: 'std::unique_ptr>::unique_ptr>(_Ptr2,_Dx2)' : attempting to reference a deleted function with [ _Ptr2=const char * , _Dx2=main:: ] C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\VC\\INCLUDE\\memory(16 16) : see declaration of 'std::unique_ptr>::unique_ptr' main.cpp(8):错误C2280:'std :: unique_ptr> :: unique_ptr>(_ Ptr2,_Dx2)':尝试用[_Ptr2 = const char *,_Dx2 = main ::] C:引用已删除的函数程序文件(x86)\\ Microsoft Visual Studio 12.0 \\ VC \\ INCLUDE \\ memory(16 16):请参阅'std :: unique_ptr> :: unique_ptr'的声明

This appears to be a defect in the Visual C++ 2013 standard library. 这似乎是Visual C ++ 2013标准库中的一个缺陷。 I cannot reproduce the problem on 2015. 我无法在2015年重现这个问题。

The unique_ptr class has this constructor for taking a pointer and a deleter: unique_ptr类有这个构造函数用于获取指针和删除器:

unique_ptr(pointer _Ptr,
    typename _If<is_reference<_Dx>::value, _Dx,
        const typename remove_reference<_Dx>::type&>::type _Dt) _NOEXCEPT
    : _Mybase(_Ptr, _Dt)
    {   // construct with pointer and (maybe const) deleter&
    }

However, the unique_ptr<T[]> specialization also has a catch-all constructor: 但是, unique_ptr<T[]>还有一个catch-all构造函数:

template<class _Ptr2,
    class _Dx2>
    unique_ptr(_Ptr2, _Dx2) = delete;

This version is preferred over the previous one. 此版本优于前一版本。

However, because the non-specialized unique_ptr doesn't have it at all, changing u_ptr to a const char instead of const char[] fixes the problem. 但是,因为非专用的unique_ptr根本没有它,所以将u_ptr更改为const char而不是const char[]解决问题。

Using the array version with a deleter like you're doing is also unnecessary: 像你正在做的那样使用带有删除器的数组版本也是不必要的:

  1. If you want to call delete[] on your pointer, there's already a specialization for arrays. 如果要在指针上调用delete[] ,则已经有了数组专门化。 You don't need a custom deleter. 您不需要自定义删除器。

  2. If you want to do something else, you should use the non-specialized version. 如果您想要做其他事情,您应该使用非专业版。

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

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