11

While reading about multithreading in C++11, I noticed that some tutorials do this:

std::thread(print_message, "Hello").detach();

// instead of...

std::thread t(print_message, "Hello");
t.detach();

My questions are:

  1. In general, is it safe to call non-const member functions for temporary (rvalue) objects?
  2. In particular, is it safe to do so for a C++11 std::thread?
Log
  • 239
  • 1
  • 5
  • 1
    For point 1: it's safe to call member functions that don't have a precondition (for class types etc in namespace std). –  Aug 21 '15 at 15:55

3 Answers3

11
  1. Yes: the non-const function gets executed while the object is still alive, so there is no problem.
  2. Yes: std::thread behaves as any other type.
Paolo M
  • 12,403
  • 6
  • 52
  • 73
  • 2
    We should also mention that when calling `detach`, the parent thread usually doesn't care about keeping a reference to the child. When calling `join`, however, it should. – AndyG Aug 21 '15 at 13:22
6

To elaborate more on the second question, the temporary std::thread object behaves like any other temporary object:

It is destroyed after the full expression it is bound to is evaluated, which means the destructor is always called after the .detach() call - std::terminate() is not called.

Community
  • 1
  • 1
milleniumbug
  • 15,379
  • 3
  • 47
  • 71
1

In answer to question 1: You are not allowed to modify anonymous temporaries of "non-class" type (i.e.. built-in types). You are, however, allowed to call non-const member functions on anonymous temporaries of "class" type. See Section 3.10.10 in C++ ISO/IEC 14882:1998 standard.