Is std::map creating a new non const copy of object from its const reference

Viewed 106

Consider the following code .

#include <iostream>
#include <map>

class A{

public:
    int m_id;
    int m_x;
    int m_y;
    A() = default;
    A(int i, int j, int k) : m_id(i), m_x(j), m_y(k){}
};

void add(const A& a, std::map<int,A>& m){
    m[a.m_id] = a; 
}

void modify(std::map<int,A>& m){
    for(auto& x : m){
        x.second.m_x*=10;
        x.second.m_y/=10;
    }
}
void print(std::map<int,A>& m){
    for(const auto& x : m){
        std::cout << x.first << " : (" << x.second.m_x << ',' << x.second.m_y << ")\n";
    }
    std::cout << '\n';
}
int main(int argc, char const *argv[])
{   
    std::map<int,A> m;
    A a(1,10,100);
    add(a,m);
    print(m);
    {
        A b(2,10,200);
        add(b,m);
        print(m);
    }    

    modify(m);
    print(m);
    return 0;
}

I am creating a std::map of objects of type A. In add, I add an object to the std::map by using a const reference to that object. In modify, I am modifying values of std::map. In print, I am printing the map. Basically accessing the elements.
I add b in a different scope to test if it I get a memory error.
The code works correctly. My question is, is std::map with [] operator creating a new non const copy of the object ? Also, std::vector::push_back works fine. Does push_back also create a copy. I am not calling emplace.

1 Answers

Yes, a new object will be constructed as the element of std::map. To be precise, in m[a.m_id] = a;, if the key (i.e. a.m_id) does not already exist, a value-initialized A will be constructed as the new element of m firstly, then m[a.m_id] returns the reference to value of the new element; which is copy-assigned from a via the copy-assignment operator of A later.

If the key (i.e. a.m_id) already exists, m[a.m_id] just returns the reference to value of the existed element; which is copy-assigned from a then.

Related