【问题标题】:How to return unique_ptr of an array created inside my function?如何返回在我的函数中创建的数组的 unique_ptr?
【发布时间】: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

那么我怎样才能正确地编写我的函数呢?

【问题讨论】:

标签: c++ visual-c++ unique-ptr c++20


【解决方案1】:

原来问题与 C++20 模块有关,我在此代码上方执行 import std.core; 并且由于某种原因它正在导入 clang 内存模块而不是 MSVC 模块。像往常一样使用#include &lt;memory&gt; 可以解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-13
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 2011-05-18
    相关资源
    最近更新 更多