Slaus
Slaus

Reputation: 2236

Start thread without thread instance name

What is the difference between

MyClass* myClass = new MyClass;
std::thread myThread( &MyClass::MyMemberFunction, myClass );

and

std::thread( &MyClass::MyMemberFunction, myClass );

?

P.S. Trying to put boost::asio::io_service into separate thread using second approach - doesn't work. But first one does. Both approaches work if change std to boost.

WIndows 7. MSVS 12.0.

Upvotes: 0

Views: 575

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254711

The first one creates a thread object, which you must either detach or join at some point.

The second creates and destroys a temporary thread, terminating the program because you didn't detach or join it. Boost allowed that, automatically detaching threads on destruction; but that behaviour can lead to subtle errors, so the standard library forces you to make an explicit choice.

If you really want a "fire and forget" thread, you could do

std::thread( &MyClass::MyMemberFunction, myClass ).detach();

but it's usually better to keep a thread object to join at a suitable time, especially if you're planning to delete myClass at some point.

Upvotes: 5

Related Questions