c++ - shared_ptr with map(错误error C2664)

标签 c++ shared-ptr

我有一个带有 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/

相关文章:

c++ - 将 valarray 显式初始化为零有歧义吗?

c++ - 如何从 C++ 项目静态链接 golang 的 .a 库?

c++ - 解决链接器错误 : undefined reference to static class members

c++ - 引用计数智能指针的赋值运算符

c++ - 使用 std::sort 时的核心转储

c++ - 在 C++ 中扩展枚举?

c++ - 在 callback 和 main 之间传递一个变量

C++:Shared_Ptr 在虚拟方法调用上出现段错误,但不是取消引用

c++ - std::make_shared 的奇怪行为

在 boost::shared_ptr operator bool() 上旋转时需要 C++ volatile?