Ahmed
Ahmed

Reputation: 247

c++17 insert into std::map without copy object

in C++17, Why copy constructor is called on below each time std::map insert or emplace called ?.

How to insert without copying object ?.

#include <iostream>
#include <map>
class A{
public:
 A(int intID): intID(intID){
 }
 A(const A &a){
     intID = a.intID;
     std::cout << "This is Copy constructor of ID: " << intID << std::endl;
 }

private:
    int intID;
};
int main() {
    std::map<long, A> mapList;
    mapList.insert(std::pair<long,A>(123,A(123)));
    mapList.insert(std::pair<long,A>(1234,{1234}));
    mapList.emplace(std::pair<long,A>(12345,{12345}));
    mapList.emplace(123456, A(123456));
    return 0;
}

Upvotes: 0

Views: 559

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

In all the cases you're constructing an A firstly then pass it to insert and emplace, then the element will be copy-constructed from the constructed A in the container.

What you want is

mapList.emplace(123456, 123456);

Then the object will be consructed in-place with the given arguments directly.

Upvotes: 2

Related Questions