将const引用传递给std :: thread

时间:2019-09-06 02:15:49

标签: c++ reference stdthread

通过const引用传递对象,编译成功

#include <iostream>
#include <thread>

void thread_function(const std::string &s) {
  std::cout << s << std::endl;
}

int main() {
  std::string s = "hello world";
  std::thread my_thread(thread_function, s);
  my_thread.join();
  return 0;
}

但是为什么?

并在main和do_some_thing中输出s的地址,它们是不同的,似乎是复制(或移动)的引用?

#include <iostream>
#include <thread>
void do_some_thing(const std::string &s) {
  std::cout << "in do_some_thing: " <<  &s << std::endl;
}

int main() {
  std::string s = "hello world";
  std::cout << "in main: " << &s << std::endl;
  std::thread my_thread(do_some_thing, s);
  std::cout << "in main: " << &s << std::endl;
  my_thread.join();
  std::cout << "in main: " << &s << std::endl;
  return 0;
}

// the output is :
// in main: 0x7ffe26047dd0
// in main: 0x7ffe26047dd0
// in do_some_thing: 0x5631c979c288
// in main: 0x7ffe26047dd0

0 个答案:

没有答案