Skip to content

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

Open
@josuttis

Description

@josuttis

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    c++23clang:diagnosticsNew/improved warning or error message in Clang, but not in clang-tidy or static analyzerclang:memory-safetyIssue/FR relating to the lifetime analysis in Clang (-Wdangling, -Wreturn-local-addr)false-positiveWarning fires when it should not

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions