1、传递临时对象作为线程参数

    1. #include<iostream>
    2. #include<thread>
    3. using namespace std;
    4. void myPrint(const int& i, char* pmyBuf)
    5. {
    6. cout << i << endl;
    7. cout << pmyBuf << endl;
    8. }
    9. int main()
    10. {
    11. int mvar = 1;
    12. int& mvary = mvar;
    13. char mybuf[] = "this is a test!";
    14. thread mytobj(myPrint, mvar, mybuf);
    15. mytobj.detach();
    16. return 0;
    17. }

    根据debug分析,myPrint中的i并不是mvar的引用,实际是值传递。所以,即便主线程detach了子线程,那么子线程中用的i值仍然是安全的。
    但是myPrint的第二个参数指针指向的是同一个地址,因此在detach时,主线程结束了,mybuf的内存被回收了,因此会报错。所以,线程的值传递不建议传递指针,同时也不建议传递引用。

    1. #include<iostream>
    2. #include<thread>
    3. #include<string>
    4. using namespace std;
    5. void myPrint(const int& i, const string& pmyBuf)
    6. {
    7. cout << i << endl;
    8. cout << pmyBuf << endl;
    9. }
    10. int main()
    11. {
    12. int mvar = 1;
    13. int& mvary = mvar;
    14. char mybuf[] = "this is a test!";
    15. //thread mytobj(myPrint, mvar, mybuf); 不稳定
    16. thread mytobj(myPrint, mvar, string(mybuf));
    17. mytobj.detach();
    18. return 0;
    19. }

    事实上是存在,mybuf都被回收了,系统采用mybuf去转string。因此要在给线程传参是创建一个临时的string对象。