Is it safe to pass arguments by reference into a std::thread function?

前端 未结 2 1665
#include 
#include 
#include 
#include 

using namespace std;

void f(const vector& coll)
{
            


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-19 04:20

    • Is coll guaranteed to be valid before exiting this function?

      • Updated: Yes. When you pass coll to the constructor of a std::thread in main function, because coll is an object, it is decay copied. This decay copy essentially moves the vector (so it becomes rvalue), which will bind to the coll parameter in f during the execution of the thread. (Thanks for the comment by @Praetorian)
    • Is it safe to pass arguments by reference into a std::thread function?

      • Your arguments are decay copied, so you actually never pass anything by reference to std::thread.
    • Reference for std::decay: http://www.cplusplus.com/reference/type_traits/decay/

    • The accepted answer in this question std::thread with movable, non-copyable argument explained what happens to the arguments passed to std::thread

提交回复
热议问题