【问题标题】:error C2248: strange error when I use thread错误 C2248:使用线程时出现奇怪错误
【发布时间】:2012-12-26 11:03:56
【问题描述】:

我收到以下错误

错误 2 错误 C2248: 'std::thread::thread' : 无法访问私有 类中声明的成员 'std::thread' 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

我的代码

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

【问题讨论】:

    标签: c++ multithreading


    【解决方案1】:

    问题出在这行:

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

    通过取消引用,您告诉编译器您想将此对象的副本传递给线程函数。但是您的类不是可复制构造的,因为它包含 std::mutex 和 std::thread (两者都不是可复制构造的)。您遇到的错误是因为这两个类的复制构造函数无法访问。

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

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

    【讨论】:

      【解决方案2】:
      t = thread( &LoginServer::run, *this);
      

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

      当你取消引用时,一切都会崩溃,因为你的 std::threadstd::mutex 成员阻止了你的类类型的对象是可复制的——这些成员对象的复制构造函数是 private/deleted 和 是你看到的错误。

      所以:

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

      【讨论】:

      • @NikBougalis:这是LoginServer::run 函数的第一个参数通过 std::thread,但我明白你的意思。
      猜你喜欢
      • 2020-08-30
      • 2013-05-05
      • 2015-04-01
      • 1970-01-01
      • 2011-01-08
      • 2012-05-05
      • 2011-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多