#include<iostream>
#include<string>
#include<istream>
#include<thread>
using namespace std;
class MyClass
{
public:
MyClass() { cout << "构造函数" << endl; };
MyClass(const MyClass& m) { cout << "拷贝构造函数" << endl; };
~MyClass() { cout << "析构函数" << endl; };
private:
};
//值拷贝
void func_value(int a, MyClass mm) {
cout << "值拷贝" << endl;
return;
}
int main() {
int aa = 10;
MyClass my;
thread task1(func_value, aa, my);
task1.join();
return 0;
}
值传递)aa,my对象以值传递形式传递给task1指针。my对象创建调用构造函数,my对象传递给子线程调用拷贝构造,my对象传递给mm又调用一次拷贝构造,所以:
构造函数
拷贝构造函数
拷贝构造函数
值传递
析构函数
析构函数
析构函数
#include<iostream>
#include<string>
#include<istream>
#include<thread>
using namespace std;
class MyClass
{
public:
MyClass() { cout << "构造函数" << endl; };
MyClass(const MyClass& m) { cout << "拷贝构造函数" << endl; };
~MyClass() { cout << "析构函数" << endl; };
private:
};
值拷贝
//void func_value(int a, MyClass mm) {
// cout << "值传递" << endl;
// return;
//}
//指针传递
void func_p(int* a, MyClass* mm) {
cout << "指针传递" << endl;
return;
}
int main() {
int aa = 10;
MyClass my;
/*thread task1(func_value, aa, my);
task1.join();*/
thread task2(func_p, &aa, &my);
//task2.join();
task2.detach();
return 0;
}
output:
构造函数
指针传递
析构函数
指针传递)aa,my以指针的方式传递给函数指针,不会进行内存的复制,但主线程与子线程分离,主线程先执行结束释放了资源,子线程拿到的是垃圾值,该例不会,因为子线程够快,并且子线程也没访问a,mm内容。
#include<iostream>
#include<string>
#include<istream>
#include<thread>
using namespace std;
class MyClass
{
public:
MyClass() { cout << "构造函数" << endl; };
MyClass(const MyClass& m) { cout << "拷贝构造函数" << endl; };
~MyClass() { cout << "析构函数" << endl; };
private:
};
值拷贝
//void func_value(int a, MyClass mm) {
// cout << "值传递" << endl;
// return;
//}
指针传递
//void func_p(int* a, MyClass* mm) {
// cout << "指针传递" << endl;
// return;
//}
//引用传递
void func_ref(int& a, MyClass& mm) {
cout << "引用传递" << endl;
return;
}
int main() {
int aa = 10;
MyClass my;
/*thread task1(func_value, aa, my);
task1.join();*/
//thread task2(func_p, &aa, &my);
task2.join();
//task2.detach();
thread task3(func_ref, ref(aa), ref(my));
task3.detach();
return 0;
}
引用传递)引用与指针的形式差不多。