【问题标题】:Thread (Attempt to use a deleted function线程(尝试使用已删除的函数
【发布时间】:2015-08-23 21:56:33
【问题描述】:

我正在关注有关线程的在线教程并收到错误消息“语义问题:尝试使用已删除的函数”。知道有什么问题吗?

#include <iostream>
#include <thread> 
#include <string>

using namespace std;

class Fctor {
public:
    void operator() (string & msg) {
        cout << "t1 says: " << msg << endl;
        msg = "msg updated";
    }
};


int main(int argc, const char * argv[]) {

    string s = "testing string " ;
    thread t1( (Fctor()), s);

    t1.join();

    return 0;
}

【问题讨论】:

  • 完整的错误是什么?
  • Fctor() 构造的对象寿命不够长,无法在线程中使用。
  • @bmargulies 不,没关系。这是另一个参数s 的问题。我猜std::ref(s) 会起作用。
  • 我看到的第一个问题是尝试将对象作为左值传递给函子,但std::thread 将左值到右值的转换应用于参数的类型,因此调用将失败,因为它不会传递左值。尝试用std::reference_wrapper (thread t1(Fctor(), std::ref(s))) 包裹它

标签: c++ multithreading


【解决方案1】:

好吧,该代码适用于 VS2015,MS-Compiler,对代码进行了以下更改:

这个

void operator() (string & msg) {
    cout << "t1 says: " << msg << endl;
    msg = "msg updated";
}

void operator() (std::string& msg) {
    std::cout << "t1 says: " << msg.c_str() << std::endl;
    msg = "msg updated";
}

还有这个

string s = "testing string " ;
thread t1( (Fctor()), s);

std::string s = "testing string ";
Fctor f;
std::thread t1(f, s);

我更改的两个主要内容是 msg.c_str(),因为流不接受字符串,而是 const char*。 其次,我把 RValue Fctor() 变成了 LValue Fctor f 并给了 f 作为参数,线程显然不带 RValues。

【讨论】:

    猜你喜欢
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 2016-04-19
    • 2020-05-02
    • 1970-01-01
    相关资源
    最近更新 更多