簡體   English   中英

C ++ 11 cmake O3選項<no matching constructor for initialization of 'std::thread'>

[英]C++11 cmake O3 option <no matching constructor for initialization of 'std::thread'>

我將C ++與CMake makefile一起使用-std=c++11

我的程序使用幾種線程方法。 我可以毫無問題地構建和執行程序。

但是,當我在CMake選項上添加-03優化標志時,我-03此錯誤消息:

“沒有匹配的構造函數,無法初始化'std :: thread'”

首先,我不理解為什么僅在-O3選項中出現。

其次,我想在-O3進行編譯,我看到其他人在Q&A上談論mythread = std::thread(&X::run<A, B>, this, a, b); 但它在我的程序中不起作用,我也不知道如何使用。

在這里,我要介紹的功能:

static void getPoints(Mat *in, vector<Point> *posPoint, float *h,int rad, int dex,int decy, Mat *debug = NULL );

今天我用以下方法非常簡單地調用: std::thread t1(get4points,&myImage, ...

如果是std::thread(&X::run<A, B>, this, a, b); 我不明白&X::run<A, B>到底是什么,如果我在同一類的函數中調用一個類的函數。

偽代碼示例:

class myclass
{
    template<int A, int B> void run(int a, int b)
    {
        // ...
    }

    void myMainfunction(int a, int b)
    {
        ?????? -> std::thread(&this::run<int, int>, this, 1, 1);
    }
};

從代碼示例中,您必須定義所有模板參數,以指定要在線程構造函數中傳遞的具體函數。

因此,如果您有:

class myclass
{
   template<int A, int B> void run(int a, int b)
    {
    }
};

您必須為A&B指定參數,例如:

auto x = std::thread(&myclass::run<55, 66>, this, 1, 1);

如果您的方法是static ,則根本沒有相關的對象,因此將對象指針傳遞給線程構造函數沒有任何意義。 您只需寫:

class myclass
{
    template<int A, int B> static void run(int a, int b)
    {
    }
};


auto x = std::thread(&myclass::run<77, 88>, 1, 1);

你問:

如果是std :: thread(&X :: run,this,a,b); 如果我在同一類的函數中調用一個類的函數,我不明白&X :: run到底是什么。

您不了解類和對象的區別! this指向您班級的對象,而不是班級本身。 在嘗試使用模板之前,請先閱讀有關C ++的基礎知識。 如果是static函數,則沒有已提到的對象。

為了了解是否使用this指針,該對象和對非靜態函數的調用在以下示例中進行了介紹:

class myclass
{   
    private:
        int ia; 

    public:
        myclass( int _ia): ia{_ia}{}

        template<int A, int B> static void staticFun(int a, int b)
        {   
            std::cout << "Val of A: " << A << " Val of B: " << B << " a: " << a << " b: " << b << std::endl;
        }   

        template<int A, int B> void Fun(int a, int b)
        {   
            std::cout << "Val of A: " << A << " Val of B: " << B << " a: " << a << " b: " << b << " ia of instance: " << ia << std::endl;
        }   
};  

int main() 
{   
    myclass mc1(1);
    myclass mc2(2);

    auto x = std::thread(&myclass::staticFun<55, 66>, 1, 2); 
    auto y = std::thread(&myclass::Fun<77,88>, &mc1, 3, 4); 
    auto z = std::thread(&myclass::Fun<78,89>, &mc2, 5, 6); 


    x.join();
    y.join();
    z.join();
}

輸出將是這樣的:

A值:55 B值:66 a:1 b:2

A值:77 B值:88 a:3 b:4實例:1

A值:78 B值:89 a:5 b:6實例:2

但是請記住,調用std :: cout的運算符<<完全不會同步。 因此,每個線程可以隨時將其寫入流中,結果將被破壞或以任何順序出現。

暫無
暫無

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

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