c++ - Buggy expression with pre-increment operator from order of evaluation or temporary object?
问题描述
I use iterators to create substrings. I tried using the pre-increment operator in an expression, but I get unexpected results. I believe the snippet worked in part of my code, but when I cut/paste it into another function it behaved differently. Compiler was MSVC 2019.
I now believe I have an order of evaluation problem. However, do I also have any kind of problem from a temporary object?
What's the best practice for using increment operators in expressions?
using namespace std;
string str{ "The quick brown fox" };
cout << str << endl;
auto it{ begin(str) };
string str2(++it, it + 7); // Temporary object problem here?
cout << str2 << endl; // Observed "he qui". Expected "he quic".
解决方案
MSVC2019 是一个 C++17 编译器。
这里的“临时对象”没有问题。
未指定函数参数的评估顺序。它不是 实现定义的。这意味着您不能保证您可以从编译器文档中阐明行为。
所以你不知道是it + 7
使用原始值还是增量值it
。
由于为了可移植性,您应该尽量避免使用标准未指定的行为的代码,因此最佳实践是避免它。
推荐阅读
- flutter - Flutterbarcode_scan 无法得到响应
- python - 熊猫:如何解决一个系列的真值是模棱两可的
- android - 在不关闭和打开活动的情况下获取数据库中最近加载的值
- php - 表单搜索序列化 GET 参数
- javascript - 如何从集合映射中获取特定值
- javascript - 材质 UI 可搜索的选择输入不更新 UI
- typed-racket - 如何在函数定义中引用存在类型变量?
- python - 在 Python 中通过循环修改字节串的最快方法?
- node.js - Knex(或任何 NPM 包)如何运行不同版本的节点?
- python - 尝试使用 IBM Speech to Text 在 python 中读取音频文件。代码无法检测文件