首页 > 解决方案 > 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".

标签: c++

解决方案


MSVC2019 是一个 C++17 编译器。

这里的“临时对象”没有问题。

未指定函数参数的评估顺序。它不是 实现定义的。这意味着您不能保证您可以从编译器文档中阐明行为。

所以你不知道是it + 7使用原始值还是增量值it

由于为了可移植性,您应该尽量避免使用标准未指定的行为的代码,因此最佳实践是避免它。


推荐阅读