【问题标题】:Why is this not compiling? (RValue as thread CTOR arguments)为什么这不编译? (RValue 作为线程 CTOR 参数)
【发布时间】:2014-03-04 19:03:28
【问题描述】:

你好这里是我在MSVC12上写的一个测试代码。

有人能告诉我为什么当我将参数传递给线程时 std::move 没有将变量转换为 RValue refs 吗? 还有我应该怎么做。

谢谢!

///some arbitrary long task
std::string DumpFile(std::string path){
  std::this_thread::sleep_for(std::chrono::seconds(10));
  return path;
}


void run_promise(std::promise<std::string> &&_prom, std::string &&_path){
  try {
    std::string val = DumpFile(std::move(_path));
    _prom.set_value(val);
  }
  catch (...) {
    _prom.set_exception(std::current_exception());
  }
}

std::future<std::string> ADumpFile(std::string && path) {
  std::promise<std::string> prms;
  std::future<std::string> fut = prms.get_future();
  std::thread th(run_promise, std::move(prms), std::move(path));
  th.detach();
  return fut;
}

int main(int argc, char* argv []){
  auto fut = ADumpFile("toto");
  while (fut.wait_for(std::chrono::seconds(1))!=std::future_status::ready){
    std::cout << "waiting\n";
  }
  auto res = fut.get();
  getchar();
  return 0;
}

我得到的错误是:

Error 1 error C2664: 'void (std::promise<std::string> &&,std::string &&)' : cannot convert argument 2 from 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' to 'std::string &&' C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\functional 1149 1 demo11 Error 2 error C2664: 'void (std::promise<std::string> &&,std::string &&)' : cannot convert argument 1 from 'std::promise<std::string>' to 'std::promise<std::string> &&' C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\functional 1149 1 demo11

不过,如果我打电话给 run_promise(std::move(prom),std::move(path)) 我没问题。

这是与通过线程 CTOR 传递右值参数有关的问题吗?

【问题讨论】:

  • 您有一个按值获取std::promise 的函数。这是行不通的,因为std::promise 不能被复制。是的,您已将 prms 移至 thread,但 thread 不知道进一步将其实例移至 run_promise
  • 好的,我也试过这样,如果同时通过&&,我添加了错误代码。我开始怀疑我是否可以将 RValues 作为线程 CTOR 的参数传递,(线程参数是否按照应有的方式转发给函数 cal ?)

标签: multithreading c++11 move promise future


【解决方案1】:

嗯,这个问题是针对 VC11 http://connect.microsoft.com/VisualStudio/feedback/details/737812 报告的,似乎 MS 没有在 VC12 中解决。

【讨论】:

猜你喜欢
  • 2012-10-24
  • 1970-01-01
  • 1970-01-01
  • 2021-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多