#include <iostream>
using namespace std;
class background_task
{
public:
background_task()
{
cout << "默认构造" << this->m_num << endl;
}
background_task(int num)
{
this->m_num = num;
cout << "带参构造" << this->m_num << endl;
}
//void operator()()
//{
// cout << "background_task.....operator..." << endl;
//}
private:
int m_num = 20;
};
int main()
{
background_task b1; //1
background_task b2(); //2
background_task b3(10); //3
// 无区别
background_task *p1 = new background_task;
background_task *p2 = new background_task();
//对于内置类型而言,加括号是进行了初始化,不加是未进行初始化
int *p1Int = new int();
int *p2Int = new int;
//b1();
background_task(); //匿名对象
background_task(199); //匿名对象
background_task bts1 = background_task(); // 同background_task b1;
background_task bts2 = background_task(10);// 同background_task b3(10);;
return 0;
}
Analysis declare variables defined above three kinds of differences:
1, define local variables b1, automatically call the constructor function parameters without a background_task.
2, Special Note: here is equivalent to declare a function return value of the function name is background_task b2 just a statement, not implemented.
3, the definition of local variables b3, parameterized constructor automatically calls the class background_task
Note:
Comments in the code section requires special attention ::
In this case B1 () function is called overloading function void operator () ()
Sometimes we use an anonymous object passed to the function parameters, but sometimes differs from the expected:
#include <iostream>
#include <thread>
using namespace std;
class background_task
{
public:
background_task()
{
cout << "默认构造" << this->m_num << endl;
}
background_task(int num)
{
this->m_num = num;
cout << "带参构造" << this->m_num << endl;
}
void operator()()
{
cout << "background_task...Threadid:" << this_thread::get_id() << endl;
cout << "Threadnum:" << this->m_num << endl;
}
private:
int m_num = 20;
};
int main()
{
//那么此时编译器会把background_task()解释为函数声明background_task (__cdecl *)(void)
//std::thread t(background_task());
// 解决上述问题两种方案
std::thread t1((background_task()));
std::thread t2{background_task(100)};
int numA = 2000;
std::thread t3([&](){
cout << "lambda" << numA << endl;
numA = 1000;
});
t1.join();
t2.join();
t3.join();
cout << "main numA=" << numA;
return 0;
}