我是多线程新手,编程方面的知识有限。我想在 C++ 中使用异步函数来调用虚函数。下面给出了代码片段。任何帮助将非常感激。
class Binary_Genome: public Individual
{
public:
std::string evaluate_fitness();
}
class Individual
{
public:
virtual std::string evaluate_fitness()=0;
}
int main()
{
std::string w_list;
Individual* current_ind;
//Skipped some code here
std::future<std::string> future_strs;
future_strs = std::async(current_ind->evaluate_fitness); //Complier does not understand this line.
w_list = future_strs.get();
return 0;
}
编译错误:
error: invalid use of non-static member function
我理解 std::async(current_ind->evaluate_fitness) 是不正确的语法。但是,我不知道正确的语法是什么。代码在没有异步的情况下工作得很好 (w_list = current_ind->evaluate_fitness())。感谢您的帮助。
最佳答案
即使要编译,您也会遇到内存错误,因为 Individual* current_ind;
没有初始化指针。目前它指向垃圾内存地址。
你可以在 std::async
中使用指向对象的指针,例如:
Object obj;
Object* pointer = &obj;
auto fut = std::async([pointer]{ return pointer->returnSomthing(); });
确保 obj
在异步函数运行时一直存在。 std::shared_ptr
非常适合。
关于c++ - 在 C++ 中使用异步通过指针调用虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35116779/