syntax question

Hello,

Line 1 passes &C::increase_member to the thread constructor in the below code. I do not understand what &C means here. Can someone please explain? thanks in advance

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// constructing threads
#include <iostream>       // std::cout
#include <atomic>         // std::atomic
#include <thread>         // std::thread
#include <vector>         // std::vector

std::atomic<int> global_counter (0);


struct C : std::atomic<int> {
  C() : std::atomic<int>(0) {}
  void increase_member (int n) { for (int i=0; i<n; ++i) fetch_add(1); }
};

int main ()
{
  std::vector<std::thread> threads;


  std::cout << "increase counter (bar) with 10 threads using member...\n";
  C bar;
  for (int i=1; i<=10; ++i)
    threads.push_back(std::thread(&C::increase_member,std::ref(bar),1000)); // line 1

  std::cout << "synchronizing all threads...\n";
  for (auto& th : threads) th.join();

  std::cout << "global_counter: " << global_counter << '\n';
  std::cout << "foo: " << foo << '\n';
  std::cout << "bar: " << bar << '\n';

  return 0;
}
&C::increase_member is just the syntax that produces a pointer to member "increase_member" of class C.
ok, thanks. Could I use bar.increase_member instead?
No, that would be a different expression with different meaning (to be specific, it would be a pending member function call expression, which is an rvalue expression with special semantics - it can only be used as the left-hand argument of the function call operator)

Incidentally, don't derive from std::atomic<int>, it's not meant for that.
Topic archived. No new replies allowed.