简体   繁体   English

当 class 包含 std::thread 时,无法初始化对象的 std::vector

[英]Cannot initialize a std::vector of objects when class contains std::thread

I'm running into an error with a more complicated class structure which I have boiled down to the below simple test case.我遇到了一个更复杂的 class 结构的错误,我将其归结为以下简单的测试用例。 The actual intent is to use a ctor with parameters, but the error occurs even when explicitly calling the empty ctor.实际意图是使用带参数的 ctor,但即使显式调用空 ctor 也会发生错误。

class TestFun{
public:
    explicit TestFun(const std::function<void()>& fun) : m_thread(fun) {}
    ~TestFun() {m_thread.join();}
private:
    std::thread m_thread;
};

class Test : public TestFun{
public:
    Test() : TestFun( [this](){std::cout << "test\n";}) {}
};

std::vector<Test> tests(10);           // This compiles
std::vector<Test> tests(10, Test());   // This gives an error

The error is:错误是:

/usr/include/c++/11/bits/stl_uninitialized.h:288:63: error: static assertion failed: result type must be constructible from input type

What's going on here?这里发生了什么?

As stated in documentation on std::vector constructor on this line:正如这一行关于std::vector构造函数的文档中所述:

std::vector<Test> tests(10);           // This compiles

you use你用

  1. Constructs the container with count default-inserted instances of T. No copies are made.使用默认插入的计数 T 实例构造容器。不制作副本。

on another side on this line:在这条线上的另一边:

std::vector<Test> tests(10, Test());   // This gives an error

you try to use another variant:您尝试使用另一种变体:

  1. Constructs the container with count copies of elements with value value.使用具有值 value 的元素的 count 个副本构造容器。

As std::thread is not copy constructible it implicitly deletes default copy constructor of you class, so this variant does not compile.由于std::thread不是可复制构造的,它会隐式删除 class 的默认复制构造函数,因此此变体无法编译。

From std::thread documentation来自std::thread文档

No two std::thread objects may represent the same thread of execution;没有两个 std::thread 对象可以代表同一个执行线程; std::thread is not CopyConstructible or CopyAssignable, although it is MoveConstructible and MoveAssignable. std::thread 不是 CopyConstructible 或 CopyAssignable,尽管它是 MoveConstructible 和 MoveAssignable。

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

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