非常棒的std:ref
解释 https://shawnliu.me/post/passing-reference-with-std-ref-in-c++/
自己写的代码
#include <signal.h>
#include <thread>
#include <condition_variable>
#include <mutex>
#include <chrono>
#include <iostream>
class Person {
public:
Person(int age, std::string name) :age(age), name(name) {}
void profile(void) {
std::cout << "Hi my name is " << this->name << std::endl;
std::cout << "I'm " << this->age << " years old." << std::endl;
}
void setAge(int age) {
this->age = age;
}
int getAge() {
return this->age;
}
virtual ~Person() {
this->age = 0;
this->name = "";
std::cout << "Person dealloc" << std::endl;
}
private:
int age;
std::string name;
};
static Person* global_person = nullptr;
bool ask(Person&& man) {
global_person = &man;
if (man.getAge() > 18 ) {
// wait for Person deinit
std::this_thread::sleep_for(std::chrono::seconds(3));
//man.profile();
global_person->profile();
return true;
}
return false;
}
void session(void) {
Person bill(29, "zhaorui");
std::thread t(ask, std::move(bill));
t.detach();
}
int main(int argc, char* argv[]) {
session();
std::cout << "wait detached thread to end " << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(10));
global_person->profile();
return 0;
}
输出
Person dealloc
Person dealloc
wait detached thread to end
Hi my name is zhaorui
I'm 29 years old.
Person dealloc
Hi my name is
I'm 0 years old.