You can at least lesson the constructing part, depending on the insides of you mapped class. Consider the following example:
class A
{
public:
A(){};
A(int a)
: a_(a)
{
std::cout << "construct" << std::endl;
}
A& operator=(const A& b)
{
a_ = b.a_;
std::cout << "=" << std::endl;
}
A(A&& o)
: a_(o.a_)
{
std::cout << "moved" << std::endl;
}
private:
int a_;
};
It has a move constructor. By using map.emplace
you can skip the reconstruction of your classes members:
std::map<int, A> mapper;
mapper[1] = A(1);
mapper[2] = A(2);
mapper.emplace(3, std::move(mapper[2]));
mapper.erase(mapper.find(2));
This will print out the following:
construct
=
construct
=
moved
indicating that the first two are constructed but the second one is moved. You will still have to delete your element and be careful about the move semantics.
If your int a_
was replaced with something massive, you would be reducing the deep copy time and the deletion time by moving the data and deleting nothing.