本文介绍了C ++异常安全偏执:多少是太多了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

强异常安全保证说,如果发生异常,操作不会更改任何程序状态。实施异常安全副本分配的优雅方式是。



我的问题是:


  1. 使用复制和交换突变非原始类型的类的每个突变操作?


  2. 性能真的是强大的异常安全的公平交易吗? >

例如:

  b $ b {
public:
void increment()
{
//复制
tmp(* this);

//对副本执行抛出操作
++(tmp.x);
tmp.x.crazyStuff();

//现在操作完成了异常,
//改变程序状态
swap(tmp);
}

int setSomeProperty(int q)
{
A tmp(* this);
tmp.y.setProperty(q,q);
int rc = tmp.x.otherCrazyStuff();
swap(tmp);
return rc;
}

//
//和许多其他类似的
//

void swap(const A& a)
{
//不抛弃的交换
}

private:
SomeClass x;
OtherClass y;
};


解决方案


当然, const -ness / immutability和强大的保证增加对代码的信心(特别是伴随测试)。



但是,它们可能会对性能产生影响。



像所有的性能问题一样,我会说:profile和摆脱的热点。复制和交换肯定是不是实现事务语义的唯一方法(它只是最简单的),所以profiling将告诉你应该绝对不要使用它,你必须找到替代品。 / p>

The strong exception safety guarantee says that an operation won't change any program state if an exception occurs. An elegant way of implementing exception-safe copy-assignment is the copy-and-swap idiom.

My questions are:

  1. Would it be overkill to use copy-and-swap for every mutating operation of a class that mutates non-primitive types?

  2. Is performance really a fair trade for strong exception-safety?

For example:

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;
};
解决方案

As all matters of engineering, it is about balance.

Certainly, const-ness/immutability and strong guarantees increase confidence in one's code (especially accompanied with tests). They also help trim down the space of possible explanations for a bug.

However, they might have an impact on performance.

Like all performance issues, I would say: profile and get rid of the hot spots. Copy And Swap is certainly not the only way to achieve transactional semantics (it is just the easiest), so profiling will tell you where you should absolutely not use it, and you will have to find alternatives.

这篇关于C ++异常安全偏执:多少是太多了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 10:02