3 ms·
> Fix for range-based for loops Oh man, having different compilers in c++20 mode handle things differently is going to cause more grief, not less. Reminder: P
by tlb 1y ago
> Fix for range-based for loops
Oh man, having different compilers in c++20 mode handle things differently is going to cause more grief, not less.
Reminder: Prior to c++23 the following is broken:
vector<int> const &identity(vector<int> const &a) { return a; }
for (auto a : identity(vector<int>{1,2})) { ... }
That's because the lifetime of the vector isn't extended through the life of the for loop. That is, the vector is destructed right after identity returns, and the for loop ends up trying to iterate through a vector that's been destructed.
But now gcc in c++20 with -frange-for-ext-temps mode will extend the lifetime of the vector and the above code will work, and people will write code like that, and it'll break mysteriously on other c++20 compilers. The usual way it breaks is that the for loop does nothing because in destructing the vector it sets the begin and end pointers to null, so it's a subtle kind of breakage.
BTW clang with -Wall doesn't complain about the above broken code.
- pjmlp 1y agoNothing new unfortunely, when C++11 brought fresh wind into C++ and everyone raced to support it, I thought the compiler portability issues would eventually be a thing of the past. Instead, even when the ecosystem has been reduced to three major compilers, and derived forks from two of them, it has hardly changed when writing portable code. There are other examples, like supporting C++23 std in C++20 mode, not all of them support it.