开发者

Do C++ Standard Library types implement exception-safe copy-assignment?

开发者 https://www.devze.com 2023-01-25 20:08 出处:网络
I\'ve recently come to appreciate the copy-and-swap idiom, and开发者_如何学编程 have been using it to implement copy-assignment for any class which manages a resource.So it got me thinking about Stand

I've recently come to appreciate the copy-and-swap idiom, and开发者_如何学编程 have been using it to implement copy-assignment for any class which manages a resource. So it got me thinking about Standard Library types: does the standard guarantee exception-safe behavior?

For example, consider a class that contains one std::string data member. Ordinarily, I wouldn't have implemented my own copy-assignement, etc., but is this safe? Does the standard guarantee that the std::string data member is left unchanged if the copy-assignment fails? Would it be beneficial to implement copy-and-swap in this case -- or is that just going too far?


The standard specifies explicitely in 'verse' 21.4.1.2. that any other exceptions other than std::bad_length "shall have no effect".


The only reason that copy assignment for std::string would throw is if dynamic allocation failed, in which case you (arguably) are totally screwed anyway. The Standard library is the example of C++ design, and I don't think that they would have overlooked such a thing. I wouldn't go to the trouble of checking Standard types.

0

精彩评论

暂无评论...
验证码 换一张
取 消