Home > database >  When insert()ing into a std::map why is the copy-contructor called twice?
When insert()ing into a std::map why is the copy-contructor called twice?

Time:10-16

Why is the copy-constructor called twice in this code?

// main.cpp
#include <iostream>
#include <map>
#include <string>

using namespace std;

class C {
private:
  int i_;
  char c_;

public:
  C(int i, char c) : i_(i), c_(c) { cout << "ctor" << endl; }
  C(const C& other) { cout << "copy-ctor" << endl; }
};

int main(int argc, char* argv[]) {
  map<string, C> m;

  m.insert({"hello", C(42, 'c')});

  return 0;
}

Build & output:

$ g   --version && g   -g ./main.cpp && ./a.out
g   (Debian 6.3.0-18 deb9u1) 6.3.0 20170516
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

ctor
copy-ctor
copy-ctor

CodePudding user response:

The map value type is std::pair<const int, C>. C is not movable, thus std::pair<const int, C> is not movable.

m.insert({"hello", C(42, 'c')}); Creates C and copies it to a pair, local variable value in insert, then copies a pair to a map bucket.

m.emplace("hello", C(42, 'c')); will copy C only once to a bucket.

Compiler options...
Program returned: 0
Program stdout
ctor
copy-ctor
  • Related