
代码如下:
#include
#include
#include
void MyPrint(int& val,std::string& str){
std::cout< 输出结果:
10
more thread
main thread end
PS C:\Users\Administrator\Desktop\thread\build\thread可执行对象传参陷阱\Debug>
std::thread obj(myPrint,val,arr); //第一个参数传可执行对象,线程入口函数,后面传线程入口函数参数
代码如下:
#include
#include
class A{
public:
A(const int& a)
:a_(a){
std::cout<<"A的构造函数 "< 输出结果:
A的拷贝构造
A的析构函数
10
0000025EB5E71B50
A的析构函数
hhhh
PS C:\Users\Administrator\Desktop\thread\build\thread可执行对象传参陷阱2\Debug>
若传递int这种简单类型参数,建议都使用值传递,不要引用传递。防止节外生枝。
如果传递的是类对象,避免隐式类型转换。全部都在创建线程这一行就构建出临时对象来,然后在函数参数里,用引用来接收对象,防止再一次发生拷贝构造影响内存效率。
终极结论:
代码如下:
#include
#include
class A{
public:
A(int a)
:a_(a){
std::cout<<"A的构造函数: "< 输出结果:
PS D:\C++11多线程代码编写\build\thread临时对象构造时机抓捕\Debug> .\main.exe
A的构造函数: 10 this指针地址:000000C378EFF984 主线程id:2100
A的拷贝函数: 10 this指针地址:0000022C4ECA3280 主线程id:2100
A的析构函数: 10 this指针地址:000000C378EFF984 主线程id:2100
子线程MyPrint函数的参数地址: 0000022C4ECA3280 线程id:13520
A的析构函数: 10 this指针地址:0000022C4ECA3280 主线程id:13520
主线程main函数的线程id:2100
PS D:\C++11多线程代码编写\build\thread临时对象构造时机抓捕\Debug>
代码如下:
#include
#include
class A{
public:
A(int a)
:a_(a){
std::cout<<"A的构造函数: "< 输出结果:
A的构造函数: 10 this指针地址:000000F448EFFD84 主线程id:11712
A的拷贝函数: 10 this指针地址:0000024FE7102BC0 主线程id:11712
&val.a_的地址:0000024FE7102BC0
子线程MyPrint函数的参数地址: 0000024FE7102BC0 线程id:8836
A的析构函数: 100 this指针地址:0000024FE7102BC0 主线程id:8836
主线程main函数的线程id:11712
A的析构函数: 10 this指针地址:000000F448EFFD84 主线程id:11712
PS D:\C++11多线程代码编写\build\thread传递类对象、智能指针作为线程参数\Debug>
代码如下:
#include
#include
class A{
public:
A(int a)
:a_(a){
std::cout<<"A的构造函数: "< 输出结果:
PS D:\C++11多线程代码编写\build\thread传递类对象、智能指针作为线程参数\Debug> .\main.exe
A的构造函数: 10 this指针地址:0000002019B9F774 主线程id:11044
&val.a_的地址:0000002019B9F774
子线程MyPrint函数的参数地址: 0000002019B9F774 线程id:7904
主线程main函数的线程id:11044
A的析构函数: 100 this指针地址:0000002019B9F774 主线程id:11044
PS D:\C++11多线程代码编写\build\thread传递类对象、智能指针作为线程参数\Debug>
代码如下:
#include
#include
class A{
public:
A(int a)
:a_(a){
std::cout<<"A的构造函数: "< spa){
std::cout<<*spa< sp(new int(10));
// std::thread obj(MyPrint,std::ref(a));
//std::thread obj(MyPrint,sp);
std::cout< 输出结果:
0000004D7EAFF608
10
子线程MyPrint函数的参数地址: 0000004D7EEFF8A0 线程id:11876
0000004D7EAFF608
主线程main函数的线程id:15428
PS D:\C++11多线程代码编写\build\thread传递类对象、智能指针作为线程参数\Debug>
代码如下:
#include
#include
class A{
public:
A(int a)
:a_(a){
std::cout<<"A的构造函数: "< spa){
std::cout<<&spa< sp(new int(10));
// std::thread obj(MyPrint,std::ref(a));
//std::thread obj(MyPrint,sp);
// std::cout< 输出结果:
PS D:\C++11多线程代码编写\build\thread用成员函数指针做线程参数\Debug> .\main.exe
A的构造函数: 10 this指针地址:000000617A10F734 主线程id:8504
A的拷贝函数: 10 this指针地址:000001C09F7D05E4 主线程id:8504
子线程成员函数执行 this指针地址:000001C09F7D05E4 子线程id:15448
A的析构函数: 10 this指针地址:000001C09F7D05E4 主线程id:15448
主线程main函数的线程id:8504
A的析构函数: 10 this指针地址:000000617A10F734 主线程id:8504
PS D:\C++11多线程代码编写\build\thread用成员函数指针做线程参数\Debug>