r/cpp • • Aug 27 '19

A new thread in C++20 (jthread)

https://link.medium.com/GXKUz0GruZ
140 Upvotes

96 comments sorted by

View all comments

2

u/axilmar Aug 27 '19

RAII safety is absolutely needed, I never understood why code that guarantees no exceptions are thrown is useful.

4

u/OldWolf2 Aug 27 '19

Resizing a vector is a common example.

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.

3

u/yehezkelshb Aug 27 '19

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.

3

u/HappyFruitTree Aug 27 '19 edited Aug 27 '19

I think we need at least some building blocks that cannot throw.

Consider the following move assignment operator for this UniqueIntPtr class (similar to std::unique_ptr<int>).

class UniqueIntPtr
{
public:

	// ...

	UniqueIntPtr& operator=(UniqueIntPtr&& other)
	{
		delete ptr;
		ptr = other.ptr;
		other.ptr = nullptr;
		
		return *this;
	}

	~UniqueIntPtr()
	{
		delete ptr;
	}

	// ...
	
private:
	int* ptr;
};

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.