C++ 在包装类作用域为\u的线程中运行的线程缺少输出
如果要使用www.ideone.com运行此程序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 )
#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) };