我想在我的类/结构中创建一个线程对象,但不想在声明期间立即初始化。 Intead 想稍后再做。因此,我在下面的代码片段中做了,我得到了这个编译错误。我该如何解决这个问题?
error C2280: 'std::thread::thread(const std::thread &)' : attempting to reference a deleted function
我观察到导致此错误的行是:
std::thread t2;
这是否意味着我们不能只声明一个 std::thread 而不进行初始化?这与此线程中的答案相矛盾 Is it possible to define an std::thread and initialize it later?
struct Abc
{
int a;
std::thread t2;
void mem1()
{
printf("mem1\n");
}
void mem2()
{
printf("mem2\n");
std::thread t1(&Abc::mem1, Abc());
t2.swap(t1);
printf("after spawning t1\n");
t2.join();
}
};
错误详情:
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xmemory0(611): error C2280: 'std::thread::thread(const std::thread &)' : attempting to reference a deleted function 1>
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\thread(70) : see declaration of 'std::thread::thread' 1> This diagnostic occurred in the compiler generated function 'Abc::Abc(const Abc &)
最佳答案
编译器错误告诉您您正在尝试复制一个结构 Abc
,它有一个成员 std::thread
。这是不可能的,因为无法复制 std::thread
。
如果您发布了整个错误消息,包括它首先指向的代码(即实际调用 Abc
的复制构造函数的代码行),我可以为您提供更完整的解决方案。
旧答案保留在下面,但我认为它在定义您的特定问题的原因时是不正确的。关于编译器生成的移动构造函数的漫谈本身仍然有效。
您的代码没问题。编译器无法编译对 swap
的调用,在仅移动类型的情况下,它依赖于所涉及类型的移动构造函数。您的 std::thread
不会明确定义它,因此在这种情况下,符合标准的编译器会生成它。
Visual Studio 2013 不会自动生成移动构造函数。这似乎是一个他们可以解决的错误(通过为他们的 std::thread
实现明确定义它,可能还有所有其他 std
类(模板))。确保将编译器更新到 VS 2013.5(更新 5),看看是否有帮助。
如果这不起作用,请获取更新版本的 Visual Studio。不生成移动构造函数的问题在 VS 2015 中已修复。VS 2017 也已出局。后者在标准 C++ 方面要好得多,也严格得多,尽管它仍然无法编译大量“基本”SFINAE。
关于c++ - 在 C++ 中创建未初始化的 std::thread 时出现错误 C2280,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44963121/