【问题标题】:Movable parameters in std::thread constructor (Visual C++ 2012)std::thread 构造函数中的可移动参数 (Visual C++ 2012)
【发布时间】:2013-01-21 18:05:29
【问题描述】:

我在 MSVC 2012 中遇到了右值引用的问题。

#include <thread>
#include <string>
#include <future>

void foo(std::promise<std::string> &&prms) { /* some code */ }

int main() {
  std::promise<std::string> prms;
  // std::future<std::string> ftr = prms.get_future();
  std::thread th(&foo, std::move(prms));

  // some other code
}

编译器说:error C2664: 'void (std::promise<_ty> &&)' : cannot convert parameter 1 from 'std::promise<_ty>' to 'std::promise<_ty> && '

是我的错误(然后如何解决)或编译器问题(然后我想知道这种行为的起源)?

【问题讨论】:

  • @KerrekSB - 实际上,这是来自 Bartocz Milewski 的代码示例。看看his postfuture 部分)。我想知道为什么我不能编译它。
  • 我想知道为什么 Bartocz 试图兑现这个承诺。
  • @LightnessRacesinOrbit - 我猜,这是一种解决超出范围问题的方法。如果左值引用promise,则可能会出现问题
  • @Loom:这不会破坏未来吗?
  • @Loom: 嗯.. 好吧,Bartosz 的asyncFun 信守承诺。试试看。你是对的,这只有在线程是从右值引用构造的情况下才有效,因此你的原始函数与右值引用 should 也可以工作。

标签: c++ multithreading rvalue-reference visual-c++-2012 stdthread


【解决方案1】:

这是 std::thread 的 Visual C++ 2012 实现中的一个已知问题。在 Microsoft Connect 上查看以下错误:

std::thread constructor doesn't handle movable object

对该错误的回应是:

我们试图在 VC11 的开发过程中解决这个问题,但它发生了可怕的爆炸,我们不得不恢复更改。事实证明,std::thread 不能由bind() 提供支持,因为线程需要移动它的参数,并且bind() 被禁止这样做(因为绑定的函子应该被重复调用,而它们的绑定参数不被搬家)。所以我们需要重新实现std::thread的ctor来避免使用bind()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    相关资源
    最近更新 更多