简体   繁体   English

在分配的右侧使用减量运算符是否有效的C ++?

[英]Is using a predecrement operator on the right hand side of an assignment valid C++?

I almost never put a ++ or -- anywhere except on its own line. 我几乎从来没有将++或-放在自己的行上之外的任何地方。 I know they can lead to undefined behavior and can be hell for debugging. 我知道它们会导致未定义的行为,并且可能会给调试带来麻烦。 But for verbosity purposes, I'm tempted. 但是出于冗长的目的,我很受诱惑。 Is this valid code? 这是有效的代码吗?

map<int, int> dict;

...

int key = ...;
if (dict.lower_bound(key) != dict.begin()) {
  int prevval = (--dict.lower_bound(key))->second;
  ...
}

I'd like to just do 只是做

int prevval = (dict.lower_bound(key)-1)->second;

but bidirectional iterators don't have operator-() defined. 但是双向迭代器没有定义operator-()

Thanks! 谢谢!

Yes, it's perfectly valid and works as expected. 是的,它完全有效并且可以按预期工作。

Undefined behavior when using these operators usually come from modifying a variable multiple times between sequence points, which is not your case. 使用这些运算符时,不确定的行为通常是由于在序列点之间多次修改变量而引起的,这不是您的情况。

Actually you are doing an initialization and not an assignment, but that doesn't change anything. 实际上,您正在执行初始化而不是分配,但这并没有改变任何内容。

However, your code is valid, because there is no choice in the order of applying all the operators. 但是,您的代码是有效的,因为无法按应用所有运算符的顺序进行选择。 You have to be careful if an expression can be split in subexpressions which could be evaluated in arbitrary order. 如果表达式可以拆分为可以按任意顺序求值的子表达式,则必须小心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM