普通傳參
#include <iostream> #include <string> #include <thread> using namespace std; void func(string m) { cout << "&m:" << &m; cout << endl; } int main() { string s = "xxxx"; cout << "&s:" << &s << endl; thread t(func, s); t.join(); return 0; }
線程會將參數拷貝后訪問
引用傳參:常量引用
#include <iostream> #include <string> #include <thread> using namespace std; void func(const string& m) { cout << "&m:" << &m; cout << endl; } int main() { string s = "xxxx"; cout << "&s:" << &s << endl; thread t(func, s); t.join(); return 0; }
線程會將參數拷貝后訪問
引用傳參:非常量引用
#include <iostream> #include <string> #include <thread> using namespace std; void func(string& m) { cout << "&m:" << &m; cout << endl; } int main() { string s = "xxxx"; cout << "&s:" << &s << endl; thread t(func, ref(s)); t.join(); return 0; }
此時要用到std::ref()將參數轉換成引用形式,線程訪問的變量與參數變量為同一地址。
指針傳參
#include <iostream> #include <string> #include <thread> using namespace std; void func(string* m) { cout << "m:" << m; cout << endl; *m = "yyy"; } int main() { string* s = new string("xxx"); cout << "s:" << s << endl; thread t(func, s); t.join(); cout << "s:" << *s << endl; return 0; }
此時,線程中的指針與參數指針指向同一地址。