C++ C++;,共享\u ptr,请告诉我为什么我的代码出现错误?

C++ C++;,共享\u ptr,请告诉我为什么我的代码出现错误?,c++,c++11,shared-ptr,C++,C++11,Shared Ptr,获取错误- 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.25.28610\include\memory(1143,17): message : could be 'std::shared_ptr<int> &std::shared_ptr<int>::operator =(std::shared_ptr<int> &&am

获取错误-

1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.25.28610\include\memory(1143,17): message : could be 'std::shared_ptr<int> &std::shared_ptr<int>::operator =(std::shared_ptr<int> &&) noexcept'
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.25.28610\include\memory(1132,17): message : or       'std::shared_ptr<int> &std::shared_ptr<int>::operator =(const std::shared_ptr<int> &) noexcept'
1>E:\VS\HelloWorld\HelloWorld\main.cpp(14,10): message : while trying to match the argument list '(std::shared_ptr<int>, int *)'
1>Done building project "HelloWorld.vcxproj" -- FAILED.
1>C:\ProgramFiles(x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.25.28610\include\memory(1143,17):消息:可能是“std::shared\u ptr&std::shared\u ptr::operator=(std::shared\u ptr&&)noexcept”
1> C:\ProgramFiles(x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.25.28610\include\memory(1132,17):消息:或“std::shared\u ptr&std::shared\u ptr::operator=(const std::shared\u ptr&)noexcept”
1> E:\VS\HelloWorld\HelloWorld\main.cpp(14,10):消息:在尝试匹配参数列表(std::shared\u ptr,int*)时
1> 完成构建项目“HelloWorld.vcxproj”--失败。
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
shared_ptr ptr=使_共享();
int l=10;
ptr=&l;

cout您只能将另一个
std::shared_ptr
std::unique_ptr
分配给类型为
std::shared_ptr
的变量,请参阅此文档,以防止您在分配未在堆上分配的指针时出错,就像您在代码中尝试做的那样

请注意,对
std::make_shared()
的调用已经为
int
分配了内存,为什么不使用它呢

std::shared_ptr<int> ptr = std::make_shared<int>();
*ptr = 10;
std::cout << *ptr << '\n';

您收到的错误消息说明了一切。
std::shared_ptr
没有
运算符=()接受
int*
作为参数的
。也没有将
int*
隐式转换为
std::shared_ptr
,因为执行该转换的
shared_ptr
构造函数被标记为
explicit
。所有这些结合起来会使赋值
ptr=&l
无效。替换
ptr=&l;
*ptr=l;
std::shared_ptr<int> ptr = std::make_shared<int>();
*ptr = 10;
std::cout << *ptr << '\n';
auto ptr = std::make_shared<int>(10);
std::cout << *ptr << '\n';
std::shared_ptr<int> ptr;
std::shared_ptr<int> l;
*l = 10;
ptr = l;
std::cout << *ptr << '\n';