4

In C++ 11 with LLVM 6.0 on Mac OS X, I first created a pointer to a memory allocation of std::thread.

std::thread* th = new std::thread([&] (int tid) {
    // do nothing.
}, 0);

Then I tried to delete it.

delete th;

However, compiling the above code and execute it raises exception

libc++abi.dylib: terminating
Abort trap: 6
Praetorian
  • 106,671
  • 19
  • 240
  • 328
Strin
  • 677
  • 9
  • 15

1 Answers1

18

The thread you've created is joinable, and unless you join or detach it, std::terminate will be called when the destructor of the thread object executes. So you need

th->join();
delete th;

Early proposals for std::thread implicitly detached the thread in the destructor, but this was found to cause problems when the owning thread threw an exception between creation and joining of a thread instance. N2802 contains the change proposal along with illustrative examples.

The original behavior was carried over from boost::thread but it too has since deprecated implicit detach in the destructor.


Unrelated to your problem, but it is very unlikely you need to dynamically allocate the thread object, and even if you do, you should be storing it in a unique_ptr.

Praetorian
  • 106,671
  • 19
  • 240
  • 328
  • I dynamically allocate the threads in order to push them in std::vector, since std::thread does not have copy constructor. – Strin Aug 20 '14 at 06:27
  • Why by design we need to call thread->detach(), instead of the destructor of thread objects does that for us? – Strin Aug 20 '14 at 06:27
  • 4
    @Strin It doesn't need to be copyable. `std::vector` can handle move only types, and `std::thread` is moveable. As for requiring that the user call `join` or `detach`, IIRC the original `std::thread` proposal's destructor did do just that, but it was discovered to be problematic. Let me try and dig up why the change was made. – Praetorian Aug 20 '14 at 06:30
  • You can also have a look at the emplace to construct the object inplace in the vector. – filmor Aug 20 '14 at 08:42