簡體   English   中英

包裝類scoped_thread中運行的線程缺少輸出

[英]Absence of an ouput from the thread running in the wrapper class scoped_thread

如果使用www.ideone.com運行此程序

#include <iostream>
#include <thread>
#include <utility>
#include <stdexcept>

class scoped_thread
{
private:
    std::thread t;

public:
    explicit scoped_thread( std::thread t ) : t( std::move( t ) )
    {
        if ( not this->t.joinable() )
        {
            throw std::logic_error( "No thread" );
        }
    }

    ~scoped_thread()
    {
        t.join();
    }

    scoped_thread( const scoped_thread & ) = delete;
    scoped_thread & operator =( const scoped_thread & ) = delete;
};

void h()
{
    std::cout << "h() is running\n";
    for ( size_t i = 0; i < 10000; i++ );
    std::cout << "exiting h()\n";
}

void f()
{
    scoped_thread t( std::thread( h ) );
}

int main() 
{
    f();

    std::thread t( h );
    t.join();

    return 0;
}

那么輸出是

h() is running
exiting h()

對應於main中釋放的線程t

但是,缺少使用類scoped_thread啟動的線程的類似輸出。 為什么?

這是最令人頭疼的解析

scoped_thread t( std::thread( h ) );

這定義了一個函數t ,該函數采用名為hstd::thread並返回scopted_thread 要實際聲明該對象,請聲明:

scoped_thread t{ std::thread(h) };

暫無
暫無

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

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