My first question is about regular functions
#include <iostream>
#include <thread>
#include <functional>
void print() {
std::cout << "Function Value Thread running" << std::endl;
}
void printPtr() {
std::cout << "Print Ptr Thread running" << std::endl;
}
void printToBind() {
std::cout << "binding" << std::endl;
}
int main() {
// case 1
std::thread functionValue{print};
functionValue.join();
// case 2
std::thread functionPointerThread{&printPtr};
functionPointerThread.join();
// case 3
std::thread withArgs{std::bind(&printToBind)};
binding.join();
return 0;
}
In case 1, did the thread copy the whole function value into its own memory space?
In case 2, did the thread copy just a pointer to its own memory space? When invoking the function, is it still invoking a function in the main thread's memory space?
In case 3, is it the same underneath behavior as we seen in case 2?
My second question is about function members. I have the following code.
#include <iostream>
#include <thread>
#include <functional>
class MyClass {
public:
MyClass () {std::cout << "constructor" << std::endl;}
~MyClass() {std::cout << "destructor" << std::endl;}
MyClass (const MyClass& myClass) {std::cout << "copy constructor" << std::endl;}
MyClass (MyClass&& myClass) {std::cout << "move constructor" << std::endl;}
void print() {
std::cout << "Function Member Thread Running" << std::endl;
}
};
int main() {
// case 1
{
std::thread functionMemberThread{&MyClass::print, MyClass()};
functionMemberThread.join();
}
std::cout << "------------------" << std::endl;
// case 2
{
MyClass myClass;
std::thread functionMemberThread{std::bind(&MyClass::print, &myClass)};
functionMemberThread.join();
}
return 0;
}
My questions are
- In case 1, Was the temporary value
MyClass()
moved into the new thread's memory space? So in the new thread's whole life time, will this object always be valid?
- In case 2, Have we just copied a pointer into the new thread's memory space? In this case if for any reason
MyClass myClass;
has been released, will the new thread have undefined behavior?
If I run the program above by using
$ g++ -std=c++17 main.cpp -o prog -lpthread
$ ./prog
constructor
move constructor
move constructor
destructor
destructor
Function Member Thread Running
destructor
------------------
constructor
Function Member Thread Running
destructor
Can anyone help me to understand why the move constructor have been called twice? And why the destructor have been called twice before the thread running? My understanding is that if everything was moved, nothing shall be needed to be destroyed.
Thank you so much!!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…