[英]Iterator increment leading to different results in clang and gcc
我在以下代碼片段中遇到了一個奇怪的問題,導致了不同的結果。
Apple clang(用 3.8.0 和 11.0 測試)返回預期值 10,但 gcc(用 5.4.0 和 9 測試)返回 12。
#include <functional>
#include <iostream>
#include <vector>
int acc(std::function<int(int, int)> func, std::vector<int> operands) {
auto it = operands.begin();
int result = func(*it, *(++it)); // <-- causing issue, ++it not working as expected
if (operands.size() > 2) {
for (++it; it!=operands.end(); ++it) {
result = func(result, *it);
}
}
return result;
}
int main() {
std::cout << acc([](int a, int b){ return a+b; }, {3, 5, 2}) << std::endl;
}
例如,可以使用rextester.com復制它。
在調試時我發現迭代器增量++it
似乎是問題所在。 用it+1
后跟it = it + 1
語句替換它會導致兩個編譯器中的預期結果。 但是為什么編譯器之間的處理方式不同呢?
但是為什么編譯器之間的處理方式不同呢?
因為在 C++17 之前,未指定以什么順序評估 function arguments。
我建議不要在result
的初始化中調用func
。
int acc(std::function<int(int, int)> func, std::vector<int> operands) {
if (operands.empty()) throw std::out_of_range();
auto it = operands.begin();
int result = *it;
for (++it; it!=operands.end(); ++it) {
result = func(result, *it);
}
return result;
}
請注意, std::function
對於傳遞函數通常是矯枉過正的。 標准庫更喜歡模板化的高階函數,例如復制std::accumulate
template<class BinaryOperation >
int acc(BinaryOperation op, std::vector<int> operands)
其中BinaryOperation
是可調用為int(int, int)
的任何類似函數的類型,例如您的 lambda 類型
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.