我有一个带有 shared_ptr 数据成员的类。下面是一个例子
class A {
private:
shared_ptr<map<int, std::string>> _pMap;
A();
public:
A(shared_ptr<map<int, std::string>>);
A(const A& source);
A& operator=A(const A&);
};
A::A(shared_ptr<map<int, std::string>> mapPtr)
: _pMap(new std::shared_ptr<std::map<int, std::string>>()) {
_pMap = mapPtr;
A::A(const A& source) : _pMap(source._p) {}
A& A::operator=(const A& source) {
if (this == &source) {
return *this;
}
_pMap = source._pMap;
return *this;
}
当我试图用主程序中包含的头文件编译我的程序时,我收到以下错误:
error C2664: 'std::_Ptr_base<_Ty>::_Reset0' :
cannot convert parameter 1 from 'std::shared_ptr<_Ty> *'
to 'std::map<_Kty,_Ty> *
但我不确定我在哪里做这件事。请有人指导为什么会发生这种情况?
谢谢。
最佳答案
问题(或至少一个问题)在行中
A::A(shared_ptr<map<int, std::string>> mapPtr) : _pMap(new std::shared_ptr<std::map<int, std::string>>()) {
_pMap = mapPtr;
应该是
A::A(shared_ptr<map<int, std::string>> mapPtr) : _pMap(new std::map<int, std::string>()) {
_pMap = mapPtr;
但是没有必要两次初始化 _pMap - 所以对于这个构造函数最好是做
A::A(shared_ptr<map<int, std::string>> mapPtr) : _pMap(mapPtr) { }
关于c++ - shared_ptr with map(错误error C2664),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24814075/