问题描述:

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.

网友答案:

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.

相关阅读:
Top