Search code examples
c++shared-ptr

shared_ptr with map (error error C2664)


I have a class with a shared_ptr data member. Below is an example

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

When I tried to compile my program with just the header included in the main program, I receive the following error:

error C2664: 'std::_Ptr_base<_Ty>::_Reset0' : 
             cannot convert parameter 1 from 'std::shared_ptr<_Ty> *' 
             to 'std::map<_Kty,_Ty> *

But I am not sure where I am doing this. Can please someone guide as to why this might be happening?

Thanks.


Solution

  • The problem (or at least one of) is in the line

    A::A(shared_ptr<map<int, std::string>> mapPtr) : _pMap(new std::shared_ptr<std::map<int, std::string>>()) {
            _pMap = mapPtr;
    

    it should be

    A::A(shared_ptr<map<int, std::string>> mapPtr) : _pMap(new std::map<int, std::string>()) {
            _pMap = mapPtr;
    

    But there is not point to initialise _pMap twice - so for this constructor the best would be to do

    A::A(shared_ptr<map<int, std::string>> mapPtr) : _pMap(mapPtr) { }