[llvm-bugs] [Bug 32299] New: [Diagnostic request] Lifetime of temporaries in range-based for loop

via llvm-bugs llvm-bugs at lists.llvm.org
Wed Mar 15 22:38:44 PDT 2017


https://bugs.llvm.org/show_bug.cgi?id=32299

            Bug ID: 32299
           Summary: [Diagnostic request] Lifetime of temporaries in
                    range-based for loop
           Product: clang
           Version: unspecified
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P
         Component: C++11
          Assignee: unassignedclangbugs at nondot.org
          Reporter: bballo at mozilla.com
                CC: dgregor at apple.com, llvm-bugs at lists.llvm.org

Core Issue #1498 [1] / EWG Issue #120 [2] concerns the treatment of temporaries
in the range expression of a range-based for loop.

An example, taken from the EWG issue, is:

  std::vector<int> vec;
  for (int val : vec | boost::adaptors::reversed
                     | boost::adaptors::uniqued) {
    // Do stuff with val
  }

Here, while the temporary

  vec | boost::adaptors::reversed
      | boost::adaptors::uniqued

has its lifetime extended by the reference it's bound to (specified in the
lowering of the range-based for loop), the intermediate temporary

  vec | boost::adaptors::reversed

does not, resulting in references to it inside the retained temporary becoming
dangling, and the code exhibiting undefined behaviour.

One of the proposed resolutions for this issue is to extend the lifetimes of
all temporaries that appear in the range expression for the duration of the
loop.

While there has been no consensus for this (or any other) resolution so far,
the issue was discussed at the recent WG21 meeting in Kona, and Chandler
Carruth suggested that clang could be helpful and issue a diagnostic in cases
where it _would_ extend the lifetime of additional temporaries if the
resolution were adopted, to warn users about the potential lifetime error.

I would like to request that such a diagnostic be implemented. I believe that
the current behaviour (silent lifetime error leading to undefined behaviour) is
a significant "gotcha" for users of range-based for loops, and a diagnostic
along these lines would be very helpful.

[1] http://open-std.org/JTC1/SC22/WG21/docs/cwg_closed.html#1498
[2] http://cplusplus.github.io/EWG/ewg-active.html#120

-- 
You are receiving this mail because:
You are on the CC list for the bug.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-bugs/attachments/20170316/a3b46885/attachment.html>


More information about the llvm-bugs mailing list