【发布时间】:2020-07-23 07:50:38
【问题描述】:
出现错误-
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.
#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<int>没有接受int *作为参数的operator=()。也没有将int *隐式转换为std::shared_ptr<int>,因为将执行该转换的shared_ptr构造函数标记为explicit。所有这些结合起来使分配ptr = &l无效。 -
用
*ptr = l;替换ptr = &l;
标签: c++ c++11 shared-ptr