尽管右侧有异常,但仍发生C ++中的赋值 [英] Assignment in C++ occurs despite exception on the right side

查看:47
本文介绍了尽管右侧有异常,但仍发生C ++中的赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些(C ++ 14)代码,如下所示:

I have some (C++14) code that looks like this:

map<int, set<string>> junk;
for (int id : GenerateIds()) {
    try {
        set<string> stuff = GetStuff();
        junk[id] = stuff;
    } catch (const StuffException& e) {
        ...
    }
}

这有效。有时 GetStuff()会引发一个异常,它可以正常工作,因为如果发生异常,那么我就不需要垃圾地图中的值。

This works. Sometimes GetStuff() throws an exception, which works fine, because if it does, I don't want a value in the junk map then.

但是起初我是在循环中写的,这是行不通的:

But at first I'd written this in the loop, which doesn't work:

junk[id] = GetStuff();

更准确地说,即使 GetStuff()引发异常,创建 junk [id] (并分配一个空集)。

More precisely, even when GetStuff() throws an exception, junk[id] is created (and assigned an empty set).

这不是我期望的是:我希望它们以相同的方式起作用。

This isn't what I'd expect: I'd expect them to function the same way.

这里是否存在我误解的C ++原理?

Is there a principle of C++ that I've misunderstood here?

推荐答案

在C ++ 17之前,赋值运算符的左侧和右侧之间没有顺序。

Before C++17 there was no sequencing between the left- and right-hand side of assignment operators.

在C ++ 17中首次引入显式排序(首先评估右侧)。

It's first in C++17 that explicit sequencing was introduced (right-hand side is evaluated first).

这意味着评估顺序为 unspecified ,这意味着要由实现以所需的顺序执行评估,在这种情况下,它将首先评估左侧。

That means the evaluation order is unspecified, which means it's up to the implementation to perform the evaluation in the order in which it wants, and in this case it evaluates the left-hand side first.

有关更多详细信息,请参见此评估订单参考(尤其是指向20)。

See this evaluation order reference for more details (especially point 20).

这篇关于尽管右侧有异常,但仍发生C ++中的赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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