Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

c++ thread 传值

class thread_test{
public:
    void A(const int &a){
    }
};
int thread_int_1 = 2;`
std::thread NEW_THREAD(&thread_test::A,&_thread_test,thread_int_1);

为什么这里传入thread_int_1 如果A的参数为const &就不会报错 如果把const去掉就只能用std::ref来传递 const&与&传递的时候差别不是就在A中不能修改吗


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

thread_int_1 并不是直接传递给 A ,而是要传递给 thread 的构造。这里会发生一次拷贝。于是如果不用 std::ref 包装一层,不能实现对 thread_int_1 的修改。

const int & 的时候这无所谓,因为不会修改。但是,int & 的时候就不成了,所以必须用 std::ref


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...