const引用的作用是为了省去copy,而且不会带来副作用,比如临时变量超出作用域之后编译器会在编译时帮助延长变量生命周期。但是在多线程情况下如何,经过测试发现,如果const引用的变量是传给其他线程的,就会自动调用copy构造函数,copy一份,不得不说为了const引用这个特性编译器真是煞费苦心了。
class Student
{
public:
Student()
{
std::cout << __FUNCTION__ << std::endl;
}
~Student()
{
std::cout << __FUNCTION__ << std::endl;
}
Student(const Student& right)
{
std::cout << "Student(const Student& right)" << std::endl;
}
void Print() const
{
std::cout << m_count << std::endl;
}
int m_count = 0;
};
void DoThings(const Student& s)
{
for (;;)
{
s.Print();
Sleep(1000);
}
}
int main()
{
Student s;
std::thread t(DoThings, s);
for (;;)
{
s.m_count++;
Sleep(1000);
}
std::cout << "Hello World!\n";
int key;
std::cin >> key;
}
打印输出: