8

I tried to invoke std::thread perfect forwarding constructor (template< class Function, class... Args > explicit thread( Function&& f, Args&&... args );) with a pointer to function (NOT a pointer to member function), as shown in the following M(N)WE:

#include <thread>
#include <string>

static void foo(std::string query, int & x)
{
  while(true);
}

int main() {
 int i = 1;
 auto thd = std::thread(&foo, std::string("bar"), i);
 thd.join();
}

Live demo: https://godbolt.org/g/Cwi6wd

Why does the code not compile on GCC, Clang and MSVC, complaining about a missing overload of invoke (or similar names)? A function argument is a pointer to a function, so it should be a Callable, right?

Please note: I know that using a lambda would solve the problem; I want to understand why the problem arises.

5
  • @Ron: Not on my VS2015.
    – Astrinus
    Nov 2, 2017 at 8:31
  • 1
    I am using the 2013 version which doesn't support the C++14 standard. Probably time to upgrade.
    – Ron
    Nov 2, 2017 at 8:32
  • @Ron: it is C++11, actually... but you should upgrade anyway because support of C++11 by VS2013 is partial (I remember that when I switched to VS2015 I forgot frustration and nightmares about things that should have worked and they didn't, especially for code portable across compilers)
    – Astrinus
    Nov 2, 2017 at 8:50
  • 1
    @Ron, if I recall correctly older VS's allowed binding lvalue references to modifiable temporaries ( probably, the int is stored in a tuple internally ), hence it compiles Nov 2, 2017 at 8:55
  • Nit: Not a MNWE because the std::string argument is not required.
    – Arne Vogel
    Nov 2, 2017 at 13:10

3 Answers 3

6

std::thread stores copies of the arguments it is passed. Which as Massimiliano Janes pointed out, is evaluated in the context of the caller to a temporary. For all intents and purposes, it's better to consider it as a const object.

Since x is a non-const reference, it cannot bind to the argument being fed to it by the thread.

If you want x to refer to i, you need to use std::reference_wrapper.

#include <thread>
#include <string>
#include <functional>

static void foo(std::string , int & )
{
  while(true);
}

int main() {
 int i = 1;
 auto thd = std::thread(foo, std::string("bar"), std::ref(i));
 thd.join();
}

Live Example

The utility std::ref will create it on the fly.

8
  • 1
    @MassimilianoJanes - They are copied/moved by value. For all intents and purposed... But I'll clarify Nov 2, 2017 at 8:32
  • 1
    @MassimilianoJanes - Yes, I heard you the first time. And already edited Nov 2, 2017 at 8:35
  • "it's better to consider it as a const object" can you elaborate ? are you suggesting to avoid taking an rvalue reference ? if yes, why ? Nov 2, 2017 at 8:45
  • @MassimilianoJanes - I do. Because it creates ad-hoc "state" for the thread. If the thread needs a modifiable integer, it should be part of the callable. Not an rvalue reference to a temporary created outside the thread context itself. Nov 2, 2017 at 8:47
  • @MassimilianoJanes - Or at the very least, it should be a by-value parameter. Because that makes clear the fact that i's local to the thread. The rvalue reference is an eyebrow raiser. Nov 2, 2017 at 8:51
3

std::thread constructor performs a decay_copy on its arguments before invoking the callable perfect-forwarding the result to it; in your foo, you're trying to bind a lvalue reference (int& x) to an rvalue reference (to the temporary), hence the error; either take an int, an int const& or an int&& instead ( or pass a reference wrapper ).

2

Following on from StoryTeller's answer, a lambda may offer a clearer way to express this:

I think there are a couple of scenarios:

If we really do want to pass a reference to i in our outer scope:

 auto thd = std::thread([&i]
 {
     foo("bar", i);
 });

And if foo taking a reference just happens to be an historical accident:

 auto thd = std::thread([]() mutable
 {
     int i = 1;
     foo("bar", i);
 });

In the second form, we have localised the variable i and reduced the risk that it will be read or written to outside the thread (which would be UB).

3
  • 1
    Oh, I love the daisy chain of answers that is happening here :) +1 for those points about clarity. My thoughts exactly Nov 2, 2017 at 9:33
  • "Please note: I know that using a lambda would solve the problem; I want to understand why the problem arises."
    – Astrinus
    Nov 2, 2017 at 10:02
  • @Astrinus I see your point. The reason for needing std::ref is that the function object built by std::thread cannot 'know' whether it needs to capture by reference or by value, so by value is assumed (because it's safer and more logical) unless the argument type is a specialisation of std::reference_wrapper. Essentially specifying [&i] in a lambda is equivalent to passing the return type of std::ref(i) Nov 2, 2017 at 13:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.