4

I have a member function MyClass::doStuff(QString & str)

I am trying to call that function from a thread like this:

std::thread thr(&MyClass::doStuff, this);

However, that results in an error:

/usr/include/c++/4.8.2/functional:1697: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (MyClass::*)(QString&)>(MyClass*)>’ typedef typename result_of<_Callable(_Args...)>::type result_type;

So I've attempted to give it the argument:

QString a("test");
std::thread thr(&MyClass::doStuff(a), this);

However, that results in this error: lvalue required as unary ‘&’ operand

How would I go about running that member function with an argument, from a separate thread?

Metal Wing
  • 1,065
  • 2
  • 17
  • 40

1 Answers1

4

Just add the arguments to the thread's constructor:

QString a("test");
std::thread thr(&MyClass::doStuff, this, a);

As your function accepts a reference you should use std::ref() like this:

MyClass::doStuff(QString& str) { /* ... */ }

// ...

QString a("test");
std::thread thr(&MyClass::doStuff, this, std::ref(a)); // wrap references
Galik
  • 47,303
  • 4
  • 80
  • 117
  • Question: since `doStuff` ask for a reference but it is running in another thread, there is nothing stopping you from deleting `a` and you will end up with a UB? – Ceros Apr 05 '17 at 17:11
  • @Ceros Of course, if you delete a variable something else is using there will be trouble :) – Galik Apr 05 '17 at 17:13
  • 1
    what is the purpose of `std::ref` in this case? – Ceros Apr 05 '17 at 17:16
  • So apparently it's for template type deduction – Ceros Apr 05 '17 at 17:29
  • @Ceros It puts the variable in a `std::reference_wrapper` http://en.cppreference.com/w/cpp/utility/functional/ref It is needed when passing parameters that are accepted as references. – Galik Apr 05 '17 at 17:32