views:

111

answers:

3
std::thread f()
{
  void some_function(); // <- here
  return std::thread(some_function);
}

std::thread g()
{
  void some_other_function(int); // <- here
  std::thread t(some_other_function,42);
  return t;
}
+1  A: 

It's just a function declaration, as you thought. It is common (and recommended) to put function declarations in header files, but this is by no means required. They may be in function bodies.

Matthew Flaschen
+4  A: 

Lines like:

void some_function();

simply declare a function which will be defined later. Functions don't necessarily have to be declared outside of function scope.

Georg Fritzsche
What I am actually wondering is that it is in an function defintion?
Liu
@Liu: No, it is a *declaration* - it just declares that there is some function named `some_function` that returns `void` and takes no parameters. The definition presumably is somewhere later in the same file.
Georg Fritzsche
Thank you, sorry for my bad c++!
Liu
+1  A: 

Define a function returning a thread object:

std::thread f()
{

Declare an extern function with no arguments returning void (usually this is not done in local scope, but it is valid):

void some_function();

Start a thread executing that function, and return a handle to it:

return std::thread(some_function);
}

Same deal as before:

std::thread g()
{
void some_other_function(int);

But this is not valid. You can't make a copy of a thread, so technically it is not OK to make a local thread object and then return it. I'd be surprised if this compiled, but if it does, it might break when you build for the debugger.

std::thread t(some_other_function,42);
return t;
}

This would work, though:

return std::move( t );
Potatoswatter
Thank you for you detailed explanation!
Liu