简体   繁体   English

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

[英]error C2248: strange error when I use thread

I get the following errors 我收到以下错误

Error 2 error C2248: 'std::thread::thread' : cannot access private member declared in class 'std::thread' c:\\dropbox\\prog\\c++\\ttest\\ttest\\main.cpp 11 1 ttest 错误2错误C2248:'std :: thread :: thread':无法访问在类'std :: thread'中声明的私有成员c:\\ dropbox \\ prog \\ c ++ \\ ttest \\ ttest \\ main.cpp 11 1 ttest

Error 1 error C2248: 'std::mutex::mutex' : cannot access private member declared in class 'std::mutex' c:\\dropbox\\prog\\c++\\ttest\\ttest\\main.cpp 11 1 ttest 错误1错误C2248:'std :: mutex :: mutex':无法访问在类'std :: mutex'中声明的私有成员c:\\ dropbox \\ prog \\ c ++ \\ ttest \\ ttest \\ main.cpp 11 1 ttest

my code 我的代码

#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() {}

The problem is this line here: 问题是这条线在这里:

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

By dereferencing this, you are telling the compiler that you want to pass a copy of this object to the thread function. 通过取消引用,可以告诉编译器您希望将此对象的副本传递给线程函数。 But your class isn't copy constructible because it contains a std::mutex and std::thread (neither of which is copy constructible). 但是您的类不是可复制构造的,因为它包含一个std :: mutex和std :: thread(两者都不是可复制构造的)。 The errors you're getting are because of the inaccessible copy constructors for those two classes. 您得到的错误是由于这两个类的副本构造函数无法访问。

To fix it, don't dereference the object. 要修复它,请不要取消引用该对象。 The code will probably be clearer if you use a lambda anyway, like so: 如果您仍然使用lambda,则代码可能会更清晰,例如:

t = thread([this] { run(); });
t = thread( &LoginServer::run, *this);

That first argument to the member function run (implicit in direct calls) should be the this pointer, ie just this . 成员函数run第一个参数(直接调用中隐含)应该是this指针,也就是this Don't dereference it. 不要取消引用它。

When you dereference it all hell breaks loose because your std::thread and std::mutex members prevent objects of your class type from being copyable — the copy constructors of these member objects are private / delete d and that is the error you are seeing. 当您取消引用时,所有的地狱都会崩溃,因为您的std::threadstd::mutex成员阻止了您的类类型的对象可复制—这些成员对象的副本构造函数是private / delete d, 就是您所看到的错误。

So: 所以:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM