簡體   English   中英

無法在std :: thread中傳遞一維數組

[英]Can not pass 1D array in std::thread

這是針對我的實際項目的,但我舉了一個最小的示例(代碼基於Orbit中的Lightness Races示例)。

#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";}

生活在Coliru

錯誤是由於我正在使用大小為n的數組。 但是,對我來說-在實際項目中-很難改變它,因為許多代碼行都基於此。

使用向量

或者通過類型推導發生之前將數組衰減為指針來解決問題:

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

問題是,bind推斷出數組引用,然后嘗試按/按值復制它。 該語言未指定數組副本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM