lundi 2 décembre 2019

Double envoking of copy-constructor of a class passed into std::vector::emplace_back

I'd like to understand the cause of double envoking of copying-constructor in the following code:

#include <vector>
#include <thread>
#include <algorithm>
#include <functional>
#include <iostream>
#include <mutex>

std::mutex m_stdout;

class MyWorker {
public:
  MyWorker() = default;
  MyWorker(const MyWorker& mw) {
    m_stdout.lock();
    std::cout << "MyWorker coping" << std::endl;
    m_stdout.unlock();
  }

  void operator() () {}
};

int main () {
  std::vector<std::thread> vth;
  vth.reserve(4);
  MyWorker mw;
  for (int i = 4; i > 0; --i) {
    vth.emplace_back(mw);
  }
  std::for_each(vth.begin(), vth.end(), std::mem_fn(&std::thread::join));
}

stdout:

MyWorker coping
MyWorker coping
MyWorker coping
MyWorker coping
MyWorker coping
MyWorker coping
MyWorker coping
MyWorker coping

emplace_back should not make two copies, should it?

It looks like your post is mostly code; please add some more details.

Aucun commentaire:

Enregistrer un commentaire