Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/133.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在包装类作用域为\u的线程中运行的线程缺少输出_C++_Multithreading - Fatal编程技术网

C++ 在包装类作用域为\u的线程中运行的线程缺少输出

C++ 在包装类作用域为\u的线程中运行的线程缺少输出,c++,multithreading,C++,Multithreading,如果要使用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 )

如果要使用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;
}
对应于main中启动的线程
t

但是,使用类
作用域_线程
启动的线程没有类似的输出。为什么?

原因是:

这定义了一个函数
t
获取名为
h
std::thread
并返回
scopted_thread
。要实际声明对象,请改为声明:

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

这定义了一个函数
t
获取名为
h
std::thread
并返回
scopted_thread
。要实际声明对象,请改为声明:

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

scoped_线程t{std::thread(h)}
可以工作,否则它会抱怨
'scoped_thread t(std::thread)':未调用原型函数(是否打算使用变量定义?
scoped_thread t{std::thread(h)}
可以工作,否则它会抱怨
'scoped_thread t(std::thread)':未调用原型函数(是否打算使用变量定义?
scoped_thread t{ std::thread(h) };