3

More answers: C++ Thread taking reference argument failed compile


I'm creating a callable variable to which I'm assigning a lambda-function with arguments:

auto func = [](int &d) -> void { d++; }; 

How can I use this variable as a std::thread-function passing my argument?

I tried the obvious:

int i; auto t1 = std::thread(func, i); t1.join(); 

This fails with the compiler telling me that func has no no type named ‘type’ in [..]_Callable(_Args...)>::type result_type;.

EDIT: It is related to the reference of the argument. It works when I pass a pointer (int *i) or a copy (int i).

7
  • 4
    Try auto t1 = std::thread(func, std::ref(i)); Unrelated, initialize i; ub sucks =P Commented Feb 20, 2017 at 8:45
  • That's it, I just tried and it works. Before you posted your comment ;-) Commented Feb 20, 2017 at 8:47
  • There's a few duplicates to this; I was just too lazy to hunt them down (late here). Sry about that. Commented Feb 20, 2017 at 8:47
  • 1
    @SingerOfTheFall After 5+ years of actively using SO I finally understand the usefulness of duplicated questions: it's not the question which is duplicated that makes a question marked as duplicate but the answer. My question would produce the same answer! Thanks for enlightening. Commented Feb 20, 2017 at 9:00
  • 1
    It's not an issue specific to lambdas, you always need std::ref if a thread parameter is a reference type, see stackoverflow.com/questions/36341724/… Commented Feb 20, 2017 at 9:01

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.