c++ - 在 C++ 中使用异步通过指针调用虚函数

标签 c++ asynchronous

我是多线程新手,编程方面的知识有限。我想在 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/

相关文章:

c++ - 打印出 float 的内六角

c++ - 在 write() 写入的字节数少于请求的字节数后,如何让线程继续?

javascript - 在函数内部调用函数,只有在函数结束后,其余的代码才会发生

jquery - 等待 .each() 完成,假设 .each() 有 AJAX 调用

asynchronous - 异步工作流和尝试/使用的 F# 问题

c++ - 使用 aho-corasick 算法崩溃?

c++ - 将 Int 指针转换/类型转换为 char 指针,但获取 ascii 字符?

c++ - 是否可以限制类实例仅用作临时实例?

c# - 在断开连接时关闭客户端套接字

multithreading - 从不同的线程写入相邻的数组元素?