Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to call non-const member functions for rvalue objects?

Tags:

c++

c++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?
like image 336
Log Avatar asked Aug 21 '15 13:08

Log


3 Answers

  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.
like image 165
Paolo M Avatar answered Oct 05 '22 08:10

Paolo M


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.

like image 31
milleniumbug Avatar answered Oct 05 '22 08:10

milleniumbug


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.

like image 29
MadangLighthouse Avatar answered Oct 05 '22 09:10

MadangLighthouse