是否有一个强大的保证交换在C ++的设施 [英] Is there facility for a strong guaranteed exchange in C++

查看:134
本文介绍了是否有一个强大的保证交换在C ++的设施的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一个设施来交换两个具有强大异常保证的项目。那是;使交易完全进行,或者在面临异常的情况下将目标置于初始状态。目前的标准中有什么可以允许的,我还是找不到任何东西,虽然看起来很容易编写。

I have been looking for a facility to exchange two items with a strong exception guarantee. That is; to have the exchange proceed totally, or leave the target in the initial state in the face of exceptions. Is there anything included in the current standard that allows this, I have not been able to find anything, although it appears easy to write.

我以下是一个版本我把我想要的东西放在一起,但是这是不公平的,这超出了我对强的要求。出现强力保证无法测试,但无法保证可以。

What I have below is a version I put together to try out what I am looking for, however it is noexcept, which is more than my requirement of "the strong" guarantee. Is appears the "strong guarantee" cannot be tested, but the noexcept guarantee can.

#include <iostream>
#include <type_traits>

// Guarantee to exchange l and r fully
// or (not compile) leave them in the initial state
template<typename T>
void strong_exchange(T & l, T &r) noexcept
{
    using std::swap;
    static_assert( noexcept( swap(l, r) ), "Types must be noexcept swappable");
    swap(l, r);
}

struct X
{
    X()
    {
        throw "fish";
    }

    X(X &&) = delete;
};

int main(void)
{
    int a, b;
    strong_exchange(a, b);

    X i, j;
    strong_exchange(i, j);
}


推荐答案

如果副本分配不是 noexcept (或其他方式执行副本),这是不可能的。如果它是 noexcept std :: swap()应该做的事情。否则,可能没有什么可以做的。

It is impossible if copy assignment is not noexcept (or other way to perform the copy). In case it is noexcept, std::swap() should do the thing. Otherwise, there is probably nothing one can do about it.

这篇关于是否有一个强大的保证交换在C ++的设施的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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