简体   繁体   中英

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

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 ?
  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.

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.

In answer to question 1: You are not allowed to modify anonymous temporaries of "non-class" type (ie. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM