Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set value to a map without copy constructor?

Have to fill instances of a non-copyable class into a map. For example with this code:

#include <map>

class NoCopyClass
{
    public:
        NoCopyClass() {};
        NoCopyClass(int value)  {};

        NoCopyClass& operator=(const NoCopyClass&) = delete;

};

int main()
{
    std::map<int, NoCopyClass> my_map;
    my_map[3] = NoCopyClass(20);
}

This fails to compile unless you comment out the deletion of the copy constructor. You can try it out here: https://onlinegdb.com/ByBh0NubU

What is the right way to add a new map element when the class is not copyable?

Huge thanks!

like image 967
AlexGeorg Avatar asked Sep 18 '25 00:09

AlexGeorg


1 Answers

Try to use emplace() to construct the object in place instead of copying an already constructed object:

int main()
{
    std::map<int, NoCopyClass> my_map;
    my_map.emplace(3, 20);
}
like image 66
Håkon Hægland Avatar answered Sep 20 '25 14:09

Håkon Hægland