【问题标题】:Error passing a reference of vector on a thread to an object's member function将线程上的向量引用传递给对象的成员函数时出错
【发布时间】:2017-07-02 03:18:14
【问题描述】:

我有 3 个文件:future.cpp、future.hpp 和 main.cpp。我在 .hpp 中声明了一个未来类,如下所示:

class future_multithread{

private:
std::vector<std::vector<int>>my_input_list;
int number_of_cores;
int (*arbitrary_function)(std::vector<int>&);
std::vector<std::thread> thread_track;
std::vector<std::future<int>> futr;
semaphore* sem;

void control_threads(std::vector<int>&, std::promise<int>&&);
void launch_threads();

public:
future_multithread(int, std::vector<std::vector<int>>, int 
(*given_function)(std::vector<int>&));
void print();
void get_function_results(std::vector<int>&);
~future_multithread();

};

我在 void get_function_results(std::vector&) 函数中遇到问题。它的实现在.cpp中如下:

void future_multithread::get_function_results(std::vector<int>& results){
launch_threads();
for_each(futr.begin(), futr.end(), [this, &results](std::future<int>& ft){
results.push_back(ft.get());
});
}

这个函数从main.cpp调用如下,obj是对象:

`

auto th = std::thread(&future_multithread::get_function_results, &obj, &result);
th.join();`

我在 main 中有一个向量,需要由这个函数中的未来 get() 填充。由于未来的 get() 代码是阻塞的,我想在一个线程上启动它,以便我的 main 可以继续直到这个结果被更新,而不是阻塞。当我从这个函数返回一个向量时,它工作得很好。但它现在在具有传递引用的线程上失败。

我得到的错误是:

`error: cannot apply member pointer ‘((const std::_Mem_fn_base<void (future_multithread::*)(std::vector<int>&), true>*)this)->std::_Mem_fn_base<void (future_multithread::*)(std::vector<int>&), true>::_M_pmf’ to ‘* __ptr’, which is of non-class type ‘future_multithread*’
  { return ((*__ptr).*_M_pmf)(std::forward<_Args>(__args)...); }`

还有这个:

error: return-statement with a value, in function returning 'void' [-fpermissive]{ return ((*__ptr).*_M_pmf)(std::forward<_Args>(__args)...); }

我尝试了很多东西,但我无法弄清楚哪里出了问题。任何帮助表示赞赏!

【问题讨论】:

    标签: multithreading oop c++11


    【解决方案1】:

    不幸的是,您没有为 std::thread 构造函数调用提供上下文,所以我不知道 objresult 是什么类型。我假设obj 属于future_multithread 类型,result 属于std::vector&lt;int&gt;。在这种情况下,错误是您传递的是指向向量而不是引用的指针:您应该将 &amp;result 更改为 result

    【讨论】:

    • 我试过这样做。那没起效。你说得对,obj 的类型是 future_multithread,结果是 vector。我将 &result 更改为我的主要结果。我得到了不同的错误:error: no type named ‘type’ in ‘class std::result_of&lt;std::_Mem_fn&lt;void (future_multithread::*)(std::vector&lt;int&gt;&amp;)&gt;(future_multithread**, std::vector&lt;int&gt;)&gt;’ typedef typename result_of&lt;_Callable(_Args...)&gt;::type result_type;
    • 这个地方看起来很可疑:“future_multithre‌​ad**”。不是指针,而是指向指针的指针。你能分享一些应该编译的代码吗?这会有很大帮助
    猜你喜欢
    • 1970-01-01
    • 2020-09-06
    • 2013-12-26
    • 2021-06-24
    • 2017-05-16
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多