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

发布于 2024-09-19 06:39:44 字数 240 浏览 1 评论 0原文

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

惜醉颜 2024-09-26 06:39:44

像这样的行:

void some_function();

简单地声明一个稍后定义的函数。函数不一定必须在函数作用域之外声明。

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.

你丑哭了我 2024-09-26 06:39:44

正如您所想,这只是一个函数声明。将函数声明放在头文件中是常见的(也是推荐的),但这绝不是必需的。它们可能在功能体中。

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.

颜漓半夏 2024-09-26 06:39:44

定义一个返回 thread 对象的函数:

std::thread f()
{

声明一个没有参数的 extern 函数,返回 void (通常这不是在本地范围内完成的,但它有效):

void some_function();

启动一个执行该函数的线程,并返回它的句柄:

return std::thread(some_function);
}

与以前相同:

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

但这无效。您无法创建线程的副本,因此从技术上讲,创建本地 thread 对象然后返回它是不行的。如果编译成功,我会感到惊讶,但如果编译成功,当您为调试器构建时,它可能会中断。

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

不过,这会起作用:

return std::move( t );

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 );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文