lundi 26 mars 2018

multiple emplace_back calling copy constructor additionally

Consider the below example :

#include <iostream>
#include <vector>

class S {
public:
  S() { puts("S()"); }
  S(int) { puts("S(int)"); }
  ~S() { puts("~S()"); }
  S(const S &) { puts("S(const S&)"); }
  S(S &&) { puts("S&&"); }
  const S &operator=(const S &s) {
    puts("=");
    return s;
  }
  S &operator=(S &&s) {
    puts("Move =");
    return s;
  }
};

int main() {
  std::vector<S> s;
  s.emplace_back();
  s.emplace_back(6);
}

O/p :

S()
S(int)
S(const S&)
~S()
~S()
~S()

When only one element is emplaced_back, the constructor/destructor pair are called exactly once. But when there are multiple emplace_back (like s.emplace_back(6);), the copy constructor is also called. Why is this behavior difference ? is there still a copy exists with emplace_back ?

Aucun commentaire:

Enregistrer un commentaire