C++,Shared_ptr,请告诉我为什么我的代码出错?

C++,Shared_ptr, Please tell me why my code is giving an error?

出现错误-

1>C:\Program Files (x86)\Microsoft Visual Studio19\Community\VC\Tools\MSVC.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 Studio19\Community\VC\Tools\MSVC.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.
#include <iostream>
#include <vector>
#include <algorithm>
#include<string>
#include  <memory>

using namespace std;

int main()
{
    shared_ptr<int> ptr = make_shared<int>();
    int l = 10;
    ptr = &l;
    cout << (*ptr) << endl;

    cin.get();
}

您只能将另一个 std::shared_ptr<>std::unique_ptr<> 分配给类型为 std::shared_ptr<> 的变量,请参阅 std::shared_ptr<>::operator=() 的文档 这可以防止您在以下位置犯错误您为它分配了一个未在堆上分配的指针,就像您在代码中尝试做的那样。

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

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';

如果您真的想将另一个指针分配给 ptr,那么您应该确保该指针也是共享的或唯一的,如下所示:

std::shared_ptr<int> ptr;
std::shared_ptr<int> l;
*l = 10;
ptr = l;
std::cout << *ptr << '\n';