【发布时间】:2021-01-13 07:47:46
【问题描述】:
我尝试了各种编写函数的方法,但都因某种错误而失败。
首先,我在唯一指针上尝试了直接的const auto 类型(与const unique_ptr<char[]> 相同的结果):
export unique_ptr<char[]> mem_new_dup(const char* data, const size_t length)
{
const auto mem = make_unique<char[]>(length);
memcpy(mem.get(), data, length);
return mem; // error is on this line
}
// error:
//1>F:\gitrepos\ve2\ve2\utilities.ixx(10,1): error C2280: 'std::unique_ptr<char [],std::default_delete<char []>>::unique_ptr(const std::unique_ptr<char [],std::default_delete<char []>> &)': attempting to reference a deleted function
//1>D:\a01\_work\2\s\binaries\x86ret\inc\memory(2686): message : see declaration of 'std::unique_ptr<char [],std::default_delete<char []>>::unique_ptr'
//1>D:\a01\_work\2\s\binaries\x86ret\inc\memory(2686,5): message : 'std::unique_ptr<char [],std::default_delete<char []>>::unique_ptr(const std::unique_ptr<char [],std::default_delete<char []>> &)': function was explicitly deleted
然后我尝试从唯一指针中删除const(即使它是常量):
export unique_ptr<char[]> mem_new_dup(const char* data, const size_t length)
{
auto mem = make_unique<char[]>(length);
memcpy(mem.get(), data, length);
return mem;
}
// error
//1>D:\a01\_work\2\s\binaries\x86ret\inc\memory(2536,1): error C2070: '_Ty': illegal sizeof operand
//1> with
//1> [
//1> _Ty=char []
//1> ]
//1>D:\a01\_work\2\s\binaries\x86ret\inc\memory(2535): message : while compiling class template member function 'void std::default_delete<char []>::operator ()(_Ty (*)) noexcept const'
//1> with
//1> [
//1> _Ty=char []
//1> ]
//1>D:\a01\_work\2\s\binaries\x86ret\inc\memory(2647): message : see reference to function template instantiation 'void std::default_delete<char []>::operator ()(_Ty (*)) noexcept const' being compiled
//1> with
//1> [
//1> _Ty=char []
//1> ]
//1>D:\a01\_work\2\s\binaries\x86ret\inc\memory(2574): message : see reference to class template instantiation 'std::default_delete<char []>' being compiled
//1>F:\gitrepos\ve2\ve2\utilities.ixx(7): message : see reference to class template instantiation 'std::unique_ptr<char [],std::default_delete<char []>>' being compiled
//1>D:\a01\_work\2\s\binaries\x86ret\inc\memory(2536,25): error C2338: can't delete an incomplete type
//1>D:\a01\_work\2\s\binaries\x86ret\inc\memory(2537,1): warning C4156: deletion of an array expression without using the array form of 'delete'; array form substituted
那么我怎样才能正确地编写我的函数呢?
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。
标签: c++ visual-c++ unique-ptr c++20