gsamaras
gsamaras

Reputation: 73444

Can not pass 1D array in std::thread

This is for my actual project, but I made a minimal example (code is based on an example of Lightness Races in Orbit).

#include <thread>
#include <iostream>

class Foo
{
    Foo(int n = 10)
    {
        size_t a[n];
        constexpr int p = 5;
        std::thread threads[p];
        for (int i = 0; i < p; ++i)
            threads[i] = std::thread(std::bind(&Foo::bar, this, a, n));

        for (auto& th : threads) th.join();
    }

    void bar(size_t* a, int n) {}
};

int main() {std::cout << "ok\n";}

Live On Coliru

The error comes by the fact that I am using an array that has n as its size. However, it will be very difficult for me -in the real project- to change that, since many lines of code are based on that.

Upvotes: 1

Views: 98

Answers (1)

sehe
sehe

Reputation: 393809

Use a vector

Or solve the problem by decaying the array into a pointer before type deduction takes place:

std::bind(&Foo::bar, this, +a, n)

The problem is, bind is deducing an array reference and then tries to copy it /by value/. Array copy is not specified by the language.

Upvotes: 7

Related Questions