据我了解,函数名称本身就是指向它的指针。
因此,当我有一个函数时,我可以通过简单地将它的地址传递给线程构造函数来创建一个线程,如下所示:
void thread_function {
}
std::thread threadObj1(thread_function);
我的困惑是在将非静态成员函数的地址传递给线程时。例如:
class ClassA
{
public:
void nonstatic_function()
{
}
};
ClassA instance;
std::thread threadObj2(ClassA::nonstatic_function, &instance);
传递这样一个函数的地址有两种方式:
ClassA::nonstatic_function
&ClassA::nonstatic_function
为什么多了一个&
?如果确实需要它,那么为什么即使没有它编译器也不会报错?
最佳答案
As I understand, the name of a function itself serves as a pointer to it.
此行为继承自 C,仅适用于自由函数或静态成员函数。
对于非静态成员函数,没有到成员指针的隐式转换。指向成员的指针与自由函数指针有着根本的不同,因为它不能在不提供对象实例的情况下被调用。
If it is indeed needed, then how come the compiler does not complain even without it?
我猜你正在使用一个带有非标准扩展的编译器来允许在这种情况下省略 &
。我相信旧版本的 MSVC 允许省略它;和 gcc/Windows defaults to allowing this for MSVC compatibility 。
关于c++ - 为什么在C++中多了一个&来传递非静态成员函数的地址给线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56553411/