尽管右侧有异常,但仍发生C ++中的赋值

编程入门 行业动态 更新时间:2024-10-28 20:21:36
本文介绍了尽管右侧有异常,但仍发生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 ++中的赋值

本文发布于:2023-10-29 17:11:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1540283.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:赋值   但仍   异常   发生

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!