强大的异常安全保证表明,如果发生异常,操作不会改变任何程序状态。实现异常安全的复制分配的一种优雅方式是复制和交换习语。
我的问题是:
对变异非原始类型的类的每个变异操作使用复制和交换会不会过大?
性能真的是强异常安全的公平交易吗?
例如:
class A
{
public:
void increment()
{
// Copy
A tmp(*this);
// Perform throwing operations on the copy
++(tmp.x);
tmp.x.crazyStuff();
// Now that the operation is done sans exceptions,
// change program state
swap(tmp);
}
int setSomeProperty(int q)
{
A tmp(*this);
tmp.y.setProperty("q", q);
int rc = tmp.x.otherCrazyStuff();
swap(tmp);
return rc;
}
//
// And many others similarly
//
void swap(const A &a)
{
// Non-throwing swap
}
private:
SomeClass x;
OtherClass y;
};