有人可以解释以下奇怪的函数声明吗?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
像这样的行:
简单地声明一个稍后定义的函数。函数不一定必须在函数作用域之外声明。
Lines like:
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.
定义一个返回
thread
对象的函数:声明一个没有参数的
extern
函数,返回void
(通常这不是在本地范围内完成的,但它有效):启动一个执行该函数的线程,并返回它的句柄:
与以前相同:
但这无效。您无法创建线程的副本,因此从技术上讲,创建本地
thread
对象然后返回它是不行的。如果编译成功,我会感到惊讶,但如果编译成功,当您为调试器构建时,它可能会中断。不过,这会起作用:
Define a function returning a
thread
object:Declare an
extern
function with no arguments returningvoid
(usually this is not done in local scope, but it is valid):Start a thread executing that function, and return a handle to it:
Same deal as before:
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.This would work, though: