1. Problem description
1.1 problem description
when CPP11 creates a child thread, it uses the class as a parameter. Although only one child thread is created, the copy constructor is called many times, which is counterintuitive, cannot be explained, and there is no similar problem with the search. I hope to get the guidance of the god
.2. The environmental background of the problem and what methods have you tried
2.1 question background
when writing a sensor network simulator, in which the nodes of each sensor run independently and do not affect each other, we began to learn the multithreading of CPP11, using each thread to deal with a sensor separately, and then looked at the data that mentioned that we could use classes as callable objects to achieve thread creation, but in the process of trying, it was found that the replication constructor for creating a child thread was called twice. The destructor is called three times, the constructor is called once, minus the constructor and destructor calls in the main thread, the assignment constructor in the subthread is called twice, and the destructor is called twice. This result is different from the final demonstration in the tutorial, because the copy constructor in the tutorial is called only once
.2.2 Solutions that have been tried
has searched various forums and has no similar questions
Code
< H1 > include < iostream > < / H1 > < H1 > include < thread > < / H1 >using namespace std;
class Test {
private:
int& num;
public:
Test(int& n) : num(n){
cout << "Constructor calling\n";
}
Test(const Test & t) : num(t.num){
cout << "Copy constructor calling\n";
}
~Test(){
cout << "Destructor calling\n";
}
void operator() (){
cout << "subthread calling" << endl;
}
};
int main () {
cout << "Main thread start" << endl;
int num = 10;
Test newTest(num);
thread threadobj1(newTest);
threadobj1.join();
cout << "Main thread end" << endl;
}
4. What result do you expect? What is the error message actually seen?
4.1 expected results:
you should see only one constructor, one copy constructor, and two destructors
4.2 results actually seen:
see one constructor, two copy constructors, and three destructors
5. Compilation environment:
5.1 compilation environment
Dev-CPP 5.11
5.2 interpreter:
GCC 4.8.1 64-bit Release