使用swap使赋值运算符异常安全 [英] using swap to make assignment operator exception safe

查看:90
本文介绍了使用swap使赋值运算符异常安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


以下交换技术用于使赋值运算符异常安全(即使存在异常,也就是当前对象实例的状态)是不变的。


它使用临时对象temp在此示例中,首先在a到temp ar上进行赋值。即使有异常,当前这个对象的状态也没有被破坏。


我的问题是,只有交换函数没有抛出异常时,模式才有效。如果交换函数中存在异常,则当前对象实例的状态可能仍然被破坏(交换可能会调用成员变量的赋值运算符)。我的理解是否正确?

展开 | 选择 | Wrap | 行号

解决方案

是的。您必须尝试交换,如果抛出异常,那么您将自己抛出以终止当前对象。


感谢您的评论,弱点。



我的问题不是使用交换本身,而是我上面提到的模式是否仅在交换异常安全时才有效。


是的。您将不得不尝试交换,如果抛出异常,那么您将自己抛出以终止当前对象。



问候,

George


你怎么知道交换是否异常安全? ??

Hello everyone,


The following swap technique is used to make assignment operator exception safe (means even if there is exception, the current object instance''s state is invariant).

It used a temporary object "temp" in this sample, and assignment is made on a to temp ar first. Even if there is exception, the current this object''s state is not corrupted.

My question is, the pattern works only if there is no exception thrown by swap function. If there are exception in swap function, the state of current object instance may still be corrupted (swap may invoke the assignment operator of member variables). Is my understanding correct?

Expand|Select|Wrap|Line Numbers

解决方案

Yep. You would have to try the swap and if an exception were thrown, then you would throw onw yourself to terminate the current object.


Thanks for your comments, weaknessforcats.


My question is not using swap itself, but whether or not the pattern I put above only works if swap is exception safe.

Yep. You would have to try the swap and if an exception were thrown, then you would throw onw yourself to terminate the current object.


regards,
George


And how would you know if the swap is exception safe???


这篇关于使用swap使赋值运算符异常安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆