錯(cuò)誤代碼
#include <iostream>
#include <string>
#include <thread>
void f(int i, std::string& s) {
s += " world!";
std::cout << s << std::endl;
}
int main() {
std::string s("hello");
std::thread t(f, 3, s); // 使用std::ref傳遞s的引用
t.join(); // 等待線程完成
return 0;
}
這段代碼會(huì)導(dǎo)致編譯錯(cuò)誤,因?yàn)樵贑++中,如果你嘗試在線程(std::thread)中傳遞參數(shù),那么這些參數(shù)必須是可拷貝的,或者你需要使用 std::ref 來(lái)傳遞可引用的參數(shù)。
在你的代碼中,你嘗試在線程中傳遞一個(gè)整數(shù) 3 和一個(gè) std::string 引用 s,這是不允許的,因?yàn)?std::thread 會(huì)嘗試拷貝參數(shù),而 std::string 是不可拷貝的。當(dāng)你嘗試編譯這段代碼時(shí),編譯器會(huì)報(bào)錯(cuò),指出 std::string 無(wú)法被拷貝。
要修復(fù)這個(gè)問(wèn)題,你可以使用 std::ref 來(lái)傳遞 s 作為引用,這樣可以讓線程操作同一個(gè) std::string 對(duì)象,而不是拷貝它。修改后的代碼如下:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-739740.html
#include <iostream>
#include <string>
#include <thread>
void f(int i, std::string& s) {
s += " world!";
std::cout << s << std::endl;
}
int main() {
std::string s("hello");
std::thread t(f, 3, std::ref(s)); // 使用std::ref傳遞s的引用
t.join(); // 等待線程完成
return 0;
}
這樣,線程將能夠在 s 上進(jìn)行操作,而不會(huì)觸發(fā)拷貝構(gòu)造函數(shù),避免了編譯錯(cuò)誤。但要注意在線程中訪問(wèn)共享的資源時(shí),需要小心同步操作,以避免競(jìng)態(tài)條件和數(shù)據(jù)訪問(wèn)沖突。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-739740.html
到了這里,關(guān)于thread類(lèi)中構(gòu)造的函數(shù)參數(shù)必須是可拷貝的的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!