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!
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With