我试图向一个同事演示为什么您最好将const引用传递给使用以下代码执行只读操作的函数。令我惊讶的是,它印着“它很安全!”,即使我正在更改
passedBool
当另一个线程正在休眠时。
我想知道我是否在某个地方输入了错别字,编译器是否优化了代码并通过了
通行工具
通过复制来避免一些开销,或者如果启动另一个线程会创建
通行工具
.
class myClass
{
public:
myClass(bool& iBool)
{
t = thread(&myClass::myMethod,this,iBool);
}
~myClass()
{
t.join();
}
private:
thread t;
void myMethod(bool& iBool)
{
this_thread::sleep_for(chrono::seconds(1));
if(iBool)
cout << "It's safe!" << endl;
else
cout << "It's NOT safe!!!" << endl;
}
};
void main()
{
bool passedBool = true;
cout << "Passing true" << endl;
myClass mmyClass(passedBool);
cout << "Changing value for false" <<endl;
passedBool = false;
cout << "Expect \"It's NOT safe!!!\"" <<endl;
}