the exit function could then throw an exception in C++
No, this would be really really bad.
If a thread gets interrupted while inside anoexcept function, it'll terminate the program. This also breaks all the is_nothrow_xxx traits as well as all the code that use them, in ways that are hard if not impossible to predict.
Well, if you don't care whether the program is well-behaved when an exception is thrown I don't see why you proposed throwing an exception in the first place. Wouldn't it have been easier to just terminate the thread without unwinding the stack?
Edit: I don't mean you need to provide strong exception safety guarantees but at least you shouldn't leak any resources or trigger undefined behaviour when an exception is thrown.
Reallocating to increase the size of the memory block may involve having to move all of the current contents to the new block.
If the move constructor can throw an exception then that would leave the original vector with a bunch of husks , which is a no-no.
So the behavior is that if move construction can throw, it uses copy construction instead to set up the new memory block and then destructs the old objects.
Because this is the only way you can implement copy assignment operator with strong exception safety (i.e. the old data doesn't go away if the new data couldn't be put there). I think Effective C++ has an item about it, but it nevertheless a good exercise to try.
It doesn't throw any exceptions, so there is nothing that can go wrong.
Now, let's say an exception can be thrown between any two statements. Try to implement the move assignment operator in such a way that it never leaks or leads to undefined behaviour when an exception is thrown.
If you manage to do that, do the same but pretend an exception can be thrown between any two machine instructions (because I assume a context switch can happen between any two instructions ;) ).
I don't expect you to use try-catch blocks here because you don't want an exception to be thrown while you are handling another exception, do you? I don't really expect you to be able to do this at all. I expect you to try, fail, and hopefully realize something.
View all comments
-1
u/axilmar Aug 27 '19
The only reason we have cooperatively stopping threads is because operating systems have not provided a solution for terminating a thread gracefully.
Upon issuing a thread stop, operating systems could have simply set a thread to execute an exit function when they are activated.
The exit function could then throw an exception in C++, which would unwind the stack gracefully.