Home > database >  Cannot initialize a std::vector of objects when class contains std::thread
Cannot initialize a std::vector of objects when class contains std::thread

Time:09-21

I'm running into an error with a more complicated class structure which I have boiled down to the below simple test case. The actual intent is to use a ctor with parameters, but the error occurs even when explicitly calling the empty 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?

CodePudding user response:

As stated in documentation on std::vector constructor on this line:

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

you use

  1. Constructs the container with count default-inserted instances of T. No copies are made.

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.

As std::thread is not copy constructible it implicitly deletes default copy constructor of you class, so this variant does not compile.

From std::thread documentation

No two std::thread objects may represent the same thread of execution; std::thread is not CopyConstructible or CopyAssignable, although it is MoveConstructible and MoveAssignable.

  • Related