ocebe
ocebe

Reputation: 1

Why can't std::vector<std::jthread>> can't be initialized via an std::initializer_list?

I have an 2 example codes where I have a vector of jthreads:

#include <thread>
#include <vector>
#include <iostream>

int main() {
    std::vector<std::jthread> threads;
    
    threads.emplace_back([] {
        std::cout << "New thread via .emplace_back()" << std::endl;
    });
}

Here, everything works fine as expected, but I get an error when I convert this code into something like below:

#include <thread>
#include <vector>
#include <iostream>

int main() {
    std::vector<std::jthread> threads {
        {[] {
            std::cout << "New thread during initialization" << std::endl;
        }}
    };
}

What is wrong with the second case? From what I see neither gcc nor clang supports it.

Upvotes: -1

Views: 58

Answers (1)

Tom&#225;š Dejmek
Tom&#225;š Dejmek

Reputation: 151

First of all, std::jthread has an explicit constructor. Thus:

auto lambda = [] {
        std::cout << "New thread during initialization" << std::endl;
};
std::jthread t1 = lambda; // impossible
std::jthread t2 = std::jthread(lambda); // possible

The second thing. To use the std::initializer_list<> like so, the type must be copyable (std::jthread isn't). I think the compiler would probably optimize the copy since the initializer_list is a temporary value. But sadly it is required. Technically, initializer_list has an array which holds the data.

std::vector<std::jthread> threads = {std::jthread(lambda)}; 
// error: use of deleted function 'std::jthread::jthread(const std::jthread&)'

Upvotes: 0

Related Questions