简体   繁体   English

有人可以解释以下奇怪的函数声明吗?

[英]Can someone explain the following strange function declarations?

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;
}

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. 函数不一定必须在函数范围之外声明。

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. 它们可能在功能体内。

Define a function returning a thread object: 定义一个返回thread对象的函数:

std::thread f()
{

Declare an extern function with no arguments returning void (usually this is not done in local scope, but it is valid): 声明一个extern不带参数的返回功能void (通常这不是在局部范围内进行的,但它是有效的):

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. 您无法复制线程,因此从技术上讲,创建本地thread对象然后返回它是不可行的。 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 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM