llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
29.09k stars 12k forks source link

Unnecessary warning for the fixed range-based for loop in C++23 #109793

Open josuttis opened 1 month ago

josuttis commented 1 month ago

Consider (for the complete example, see: https://www.godbolt.org/z/oajGrd56M):

std::vector<std::string> getData() {  return {"OK?", "other", "ok"}; }

for (auto c : getData()[0]) {
  std::cout << c << '\n';
}

Iterating over a reference to an rvalue was an error before C++23, but since C++23 it no longer is.

Thanks for making the approporiate fix in clang. However, there is still a warning as if we don't have the fix.

<source>:13:17: warning: object backing the pointer will be destroyed at the end of the full-expression [-Wdangling-gsl]
   13 |   for (auto c : getData()[0]) {
      |                 ^~~~~~~~~
1 warning generated.
ASM generation compiler returned: 0
<source>:13:17: warning: object backing the pointer will be destroyed at the end of the full-expression [-Wdangling-gsl]
   13 |   for (auto c : getData()[0]) {
      |                 ^~~~~~~~~

So, this warning should go away with C++23. Not sure how easy it is to fix it, though, as this is a special behavior just in the range-based for loop.

shafik commented 1 month ago

CC @hokein

hokein commented 1 month ago

Yeah, the lifetime analysis doesn't handle temporary rangeinitializer yet. I think we need to exclude this case.