std :: thread参数(值与const)

时间:2017-06-22 09:03:36

标签: c++ multithreading c++11

当我使用函数生成一个新线程(std::thread)时,该函数的参数 是按价值 - 不是通过参考。

因此,如果我使用引用参数(int& nArg)定义该函数 我的编译器(mingw 4.9.2)输出一个错误(在compilian-suaeli中就像是 “缺少复制构造函数”我猜; - )

但是,如果我将参考参数const(const int& nArg)设为它,则不会抱怨。

有人可以解释一下吗?

2 个答案:

答案 0 :(得分:1)

如果您想传递参考,由于std::reference_wrapper,您必须将其包装到std::ref。像:

<!DOCTYPE html>
<html>

<head>

  <!-- Default stylesheet provided with App.js.
    Contains iOS/Android styles for all included widgets. -->
  <link rel="stylesheet" href="//cdn.kik.com/app/2.0.1/app.min.css">


</head>

<body>

  <!-- Page1 -->
  <div class="app-page" data-page="page1">
    <div class="app-topbar">
      <h1>Page 1</h1>
    </div>
    <div class="app-content">
      <img src="https://upload.wikimedia.org/wikipedia/commons/1/13/Red_squirrel_%28Sciurus_vulgaris%29.jpg">
      <img src="https://upload.wikimedia.org/wikipedia/commons/d/d5/Lightmatter_lioness.jpg">
      <div class="app-button" data-target="page2">Go to page 2</div>
      <p>Click the images. If nothing happens, go to page2 and then back to page1 and try clicking again to see the problem I'm experiencing:
        <strong>The clicked image disappears when clicked which makes the page transition look messy.</strong></p>
    </div>
  </div>

  <!-- Page2 -->
  <div class="app-page" data-page="page2">
    <div class="app-topbar">
      <h1>Page 2</h1>
    </div>
    <div class="app-content">
      <div id="clicked-img-container"></div>
      <div class="app-button" data-target="page1">Go to page 1</div>
    </div>
  </div>

  <!-- jQuery-like library focusing on being lightweight and mobile-friendly -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.2.0/zepto.min.js"></script>

  <!-- core module containing all library functionality -->
  <script src="//cdn.kik.com/app/2.0.1/app.min.js"></script>
</body>


</html>

答案 1 :(得分:0)

std::thread的参数只使用过一次。

实际上,它将它们存储在std::tuple<Ts...> tup中。然后它执行f( std::get<Is>(std::move(tup))...)

传递std::get右值tuple意味着它可以从元组中的值或右值引用字段中获取状态。如果没有元组是一个右值,它会给它一个引用。

除非您使用reference_wrapper(即std::ref / std::cref),否则您传递给std::thread的值会在中存储为值 std::tuple。这意味着您调用的函数将rvalue传递给std::tuple中的值。

rvalues可以绑定到const&但不能绑定到&

现在,上面的std::tuple是一个实现细节,是std::thread的想象实现。标准中的措辞更加迟钝。

为什么标准会说这种情况发生?通常,您不应将&参数绑定到将立即丢弃的值。该函数认为它正在修改调用者可以看到的内容;如果该值将立即被丢弃,这通常是调用者的错误。

另一方面,

const&参数会绑定到将立即丢弃的值,因为我们将它们用于提高效率目的,而不仅仅是为了参考目的。

或者,粗略地说,因为

const int& x = 7;

是合法的

int& x = 7;

不是。第一个是逻辑上丢弃的对象const&(由于参考生命周期延长,它不是,但它在逻辑上是暂时的)。

相关问题