在 Visual Studio 中使用 std::make_shared 时出现错误 C2440

问题描述 投票:0回答:1

我可能在这里犯了一些基本错误,但谷歌没有发现任何结果。我正在使用 Visual Studio 2019,我的代码如下:

#include <memory>

int main()
{
    std::shared_ptr<double[]> sp7 = std::make_shared<double[]>(256, 2.0);
}

我直接从https://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared获取此内容,所以我有理由相信它是正确的。尽管如此,当我编译时我得到了

Error   C2440   '=': cannot convert from '_Ux (*const )' to 'double *'

双击此错误将我带入一些名为

_Set_ptr_rep_and_enable_shared
的函数模板的内部,它并没有告诉我太多信息。完整的构建输出是

Build started...
1>------ Build started: Project: Mem, Configuration: Debug Win32 ------
1>Mem.cpp
1>C:\[MSVCdir]\include\xmemory(1893,9): warning C4200: nonstandard extension used: zero-sized array in struct/union
1>C:\[MSVCdir]\include\xmemory(1893,9): message : This member will be ignored by a defaulted constructor or copy/move assignment operator
1>C:\[MSVCdir]\include\memory(2027): message : see reference to class template instantiation 'std::_Wrap<_Ty>' being compiled
1>        with
1>        [
1>            _Ty=double []
1>        ]
1>C:\[MSVCdir]\include\memory(2725): message : see reference to class template instantiation 'std::_Ref_count_obj2<_Ty>' being compiled
1>        with
1>        [
1>            _Ty=double []
1>        ]
1>C:\[localdir]\Test\Mem\Mem.cpp(5): message : see reference to function template instantiation 'std::shared_ptr<double []> std::make_shared<double[],int,double>(int &&,double &&)' being compiled
1>C:\[MSVCdir]\include\memory(1770,1): error C2440: '=': cannot convert from '_Ux (*const )' to 'double *'
1>        with
1>        [
1>            _Ux=double []
1>        ]
1>C:\[MSVCdir]\include\memory(1770,22): message : Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>C:\[MSVCdir]\include\memory(2725): message : see reference to function template instantiation 'void std::shared_ptr<double []>::_Set_ptr_rep_and_enable_shared<_Ty>(_Ux (*const ),std::_Ref_count_base *const ) noexcept' being compiled
1>        with
1>        [
1>            _Ty=double [],
1>            _Ux=double []
1>        ]
1>C:\[MSVCdir]\include\memory(2728): message : see reference to function template instantiation 'void std::shared_ptr<double []>::_Set_ptr_rep_and_enable_shared<_Ty>(_Ux (*const ),std::_Ref_count_base *const ) noexcept' being compiled
1>        with
1>        [
1>            _Ty=double [],
1>            _Ux=double []
1>        ]
1>C:\[localdir]\Test\Mem\Mem.cpp(5): message : see reference to function template instantiation 'std::shared_ptr<double []> std::make_shared<double[],int,double>(int &&,double &&)' being compiled
1>Done building project "Mem.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
c++ visual-c++ shared-ptr
1个回答
0
投票

感谢那些指出启用最新版本的 C++ 修复了此问题的人。

© www.soinside.com 2019 - 2024. All rights reserved.