Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>#include &lt;thread&gt; #include &lt;iostream&gt; class bar { public: void foo() { std::cout &lt;&lt; "hello from member function" &lt;&lt; std::endl; } }; int main() { std::thread t(&amp;bar::foo, bar()); t.join(); } </code></pre> <p>EDIT: Accounting your edit, you have to do it like this:</p> <pre><code> std::thread spawn() { return std::thread(&amp;blub::test, this); } </code></pre> <hr> <p><strong>UPDATE:</strong> I want to explain some more points, some of them have also been discussed in the comments.</p> <p>The syntax described above is defined in terms of the INVOKE definition (§20.8.2.1):</p> <blockquote> <p>Define INVOKE (f, t1, t2, ..., tN) as follows: </p> <ul> <li>(t1.*f)(t2, ..., tN) when f is a pointer to a member function of a class T and t1 is an object of type T or a reference to an object of type T or a reference to an object of a type derived from T;</li> <li>((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a class T and t1 is not one of the types described in the previous item;</li> <li>t1.*f when N == 1 and f is a pointer to member data of a class T and t 1 is an object of type T or a<br> reference to an object of type T or a reference to an object of a<br> type derived from T;</li> <li>(*t1).*f when N == 1 and f is a pointer to member data of a class T and t 1 is not one of the types described in the previous item;</li> <li>f(t1, t2, ..., tN) in all other cases.</li> </ul> </blockquote> <hr> <p>Another general fact which I want to point out is that by default the thread constructor will copy all arguments passed to it. The reason for this is that the arguments may need to outlive the calling thread, copying the arguments guarantees that. Instead, if you want to really pass a reference, you can use a <code>std::reference_wrapper</code> created by <code>std::ref</code>.</p> <pre><code>std::thread (foo, std::ref(arg1)); </code></pre> <p>By doing this, you are promising that you will take care of guaranteeing that the arguments will still exist when the thread operates on them.</p> <hr> <p>Note that all the things mentioned above can also be applied to <code>std::async</code> and <code>std::bind</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload