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.