非常棒的std:ref解释 https://shawnliu.me/post/passing-reference-with-std-ref-in-c++/

    自己写的代码

    1. #include <signal.h>
    2. #include <thread>
    3. #include <condition_variable>
    4. #include <mutex>
    5. #include <chrono>
    6. #include <iostream>
    7. class Person {
    8. public:
    9. Person(int age, std::string name) :age(age), name(name) {}
    10. void profile(void) {
    11. std::cout << "Hi my name is " << this->name << std::endl;
    12. std::cout << "I'm " << this->age << " years old." << std::endl;
    13. }
    14. void setAge(int age) {
    15. this->age = age;
    16. }
    17. int getAge() {
    18. return this->age;
    19. }
    20. virtual ~Person() {
    21. this->age = 0;
    22. this->name = "";
    23. std::cout << "Person dealloc" << std::endl;
    24. }
    25. private:
    26. int age;
    27. std::string name;
    28. };
    29. static Person* global_person = nullptr;
    30. bool ask(Person&& man) {
    31. global_person = &man;
    32. if (man.getAge() > 18 ) {
    33. // wait for Person deinit
    34. std::this_thread::sleep_for(std::chrono::seconds(3));
    35. //man.profile();
    36. global_person->profile();
    37. return true;
    38. }
    39. return false;
    40. }
    41. void session(void) {
    42. Person bill(29, "zhaorui");
    43. std::thread t(ask, std::move(bill));
    44. t.detach();
    45. }
    46. int main(int argc, char* argv[]) {
    47. session();
    48. std::cout << "wait detached thread to end " << std::endl;
    49. std::this_thread::sleep_for(std::chrono::seconds(10));
    50. global_person->profile();
    51. return 0;
    52. }

    输出

    1. Person dealloc
    2. Person dealloc
    3. wait detached thread to end
    4. Hi my name is zhaorui
    5. I'm 29 years old.
    6. Person dealloc
    7. Hi my name is
    8. I'm 0 years old.