0

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;
}
1
  • Try to use mapList.insert(std::make_pair(1234,1234)); Commented Sep 30, 2020 at 8:48

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.