mercredi 4 septembre 2019

How std::thread object copies argument?

I instantiationed a std::string object, and std::thread supposed to copy it into it's internal storage, why the code below still doesn't work?

If I detach t(f, 5, std::string(buf)), there are no output at all !

#include <thread>
#include <iostream>
#include <unistd.h>

using namespace std;

void f(int i, const std::string &str) {
  printf("i = %d, str = %s\n", i, str.c_str());
}

void oops(int ival) {
  char *buf = new char[32]{0};
  snprintf(buf, 32, "%i", ival);
  std::thread t(f, 3, buf); // maybe danling pointer
  t.detach();

  delete [] buf; 
}

void not_oops(int ival) {
  char *buf = new char[32]{0};
  snprintf(buf, 32, "%i", ival);
  std::thread t(f, 5, std::string(buf)); // FIXME: why it won't work ?
  t.join();
  delete [] buf;
}

int main() {
  oops(1992); // This is buggy
  not_oops(1999);
}

expected output: i = 3, str = 1992 i = 5, str = 1999

actual output: i = 3, str = 1999 i = 5, str = 1999

Aucun commentaire:

Enregistrer un commentaire