我是多线程新手,对编程知识有限。我想在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-&gt; evaluate_fitness)语法不正确。但是,我不知道正确的语法是什么。代码完美无需异步(w_list = current_ind-&gt; evaluate_fitness())。谢谢你的帮助。
答案 0 :(得分:2)
即使是编译,也会因为Individual* current_ind;
没有初始化指针而导致内存错误。目前它指向垃圾记忆地址。
你可以使用std::async
中的对象指针:
Object obj;
Object* pointer = &obj;
auto fut = std::async([pointer]{ return pointer->returnSomthing(); });
只要async函数运行,请确保obj
处于活动状态。 std::shared_ptr
非常适合这种情况。