Murphy M
Murphy M

Reputation: 19

why does detach thread get no output message?

I am testing a cpp code as below, and got one very confusing phenomena, below code does not print "label" string. Could anyone explain it? really thanks for your help!

class Data {
public:
  Data() { std::cout << __FUNCTION__ << std::endl; }
  ~Data() { std::cout << __FUNCTION__ << std::endl; }
  void show() { std::cout << label << std::endl; }

private:
  std::string label{"label"};
};

int main() {
  auto data = std::make_shared<Data>();
  std::thread t([=]() mutable{
    data->show();
  });

  t.detach();
}

Upvotes: 0

Views: 502

Answers (1)

Tony Tannous
Tony Tannous

Reputation: 14876

As already mentioned in comment section by Mat, nothing is preventing the program to end before thread even begins.

Change t.detach() to t.join().

From cppreference on join

waits for a thread to finish its execution

Upvotes: 3

Related Questions