Nick
Nick

Reputation: 10539

c++ assignment operator exception safety

Very straight forward question:

What is the reason of requirement that assignment operator must not throw exception?

In same time, the constructor can throw?


If you must not throw exception, how one might handle well known "custom" string example if there is not enough memory for buffer allocation?

If you just allocate less or keep old state, but do not throw exception, everything will "look" smooth, but there will be serious (hidden) error.

Upvotes: 2

Views: 2454

Answers (1)

n. m. could be an AI
n. m. could be an AI

Reputation: 119877

There is absolutely no such requirement. It is perfectly OK for an assignment to throw. In many cases throwing is unavoidable (e.g. when assignment must allocate some memory and there's none left).

What assignment should never do is leave an object in an undefined state. It must either successfully assign a new value, or leave the object in its original state (or perhaps some other valid state, which is less desirable) and throw.

This semantic is often implemented by the copy-and-swap idiom. The copy stage can throw. This leaves the assignee intact. The swap stage must never throw.

Upvotes: 8

Related Questions