SomethingSomething
SomethingSomething

Reputation: 12226

Pushing std::thread by value into a list

My code looks like the following:

#include <list>
#include <thread>

void my_function(int val) {
    // Empty function
}

int main() {
    std::list<std::thread> threads;
    for (int i = 0 ; i < 10 ; i++) {
        threads.push_back(std::thread(my_function, i));
    }

    return 0;
}

The fact that I use threads.push_back() means that I run the copy-constructor std::thread::thread(const thread&).

Please suppose that I don't know in advance how many threads I am going to need, so replacing the list by an array or by an std::vector, is not an option for me (std::vector would be an option only if I knew the number of threads in advance, as I cannot afford the vector's realloc operations).

Upvotes: 0

Views: 722

Answers (1)

The fact that I use threads.push_back() means that I run the copy-constructor

No, it does not. Since C++11 push_back is overloaded to accept an rvalue reference to the list's value type.

You cannot run std::thread's copy constructor, since it's declared as deleted. The above mentioned overload of push_back was added for this exact purpose of supporting move only types, like a thread handle.

If you want to initialize the thread directly into the container without a move, then emplace_back can do that. But you need to pass the parameters for the std::thread constructor in, not a thread that is initialized from them:

threads.emplace_back(my_function, i);

Upvotes: 6

Related Questions