错误C2248:我使用线程时出现奇怪的错误

时间:2013-01-11 19:33:41

标签: c++ multithreading

我收到以下错误

  

错误2错误C2248:' std :: thread :: thread' :无法访问私人   成员在课堂上宣布   '的std ::线程' c:\ dropbox \ prog \ c ++ \ ttest \ ttest \ main.cpp 11 1 ttest

     

错误1错误C2248:' std :: mutex :: mutex' :无法访问私人   成员在课堂上宣布   '的std ::互斥' c:\ dropbox \ prog \ c ++ \ ttest \ ttest \ main.cpp 11 1 ttest

我的代码

#include <mutex>
#include <thread>

using namespace std;

struct Serverbas
{
    mutex mut;
    thread t;
};

struct LoginServer : Serverbas
{
    void start()
    {
       t = thread(&LoginServer::run, *this);
    }
    void run() {}
};

int main() {}

2 个答案:

答案 0 :(得分:4)

问题是这一行:

t = thread( &LoginServer::run, *this);

通过解除引用,您告诉编译器您要将此对象的副本传递给线程函数。但是你的类不是可复制构造的,因为它包含一个std :: mutex和std :: thread(它们都不是可复制构造的)。您获得的错误是由于这两个类的无法访问的副本构造函数。

要修复它,请不要取消引用该对象。如果你使用lambda,代码可能会更清晰,如下所示:

t = thread([this] { run(); });

答案 1 :(得分:4)

t = thread( &LoginServer::run, *this);

成员函数run的第一个参数(在直接调用中隐含)应该是this指针,即this。不要取消引用它。

当你取消引用它时,所有地狱都会崩溃,因为你的std::threadstd::mutex成员阻止你的类类型的对象是可复制的 - 这些成员对象的副本构造函数是private / { {1}} d和 是您看到的错误。

所以:

delete
相关问题