0

If to run this program using 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;
}

then the output is

h() is running
exiting h()

that corresponds to the thread t launced in main.

However a simialr output from the thread launched using the class scoped_thread is absent. Why?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • `scoped_thread t{ std::thread( h ) };` works, otherwise it complains that `'scoped_thread t(std::thread)': prototyped function not called (was a variable definition intended?)` – Killzone Kid Mar 30 '18 at 12:55

1 Answers1

2

It's the Most Vexing Parse:

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

This defines a function t taking an std::thread named h and returning a scopted_thread. To actually declare the object, declare instead:

scoped_thread t{ std::thread(h) };
YSC
  • 38,212
  • 9
  • 96
  • 149