简体   繁体   中英

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.

There is absolutely no such requirement. It is perfectly OK for an assignment to throw. In many cases throwing is unavoidable (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM