简体   繁体   中英

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM