[clang] [libc++] Prevent calling the projection more than three times (PR #66315)

via cfe-commits cfe-commits at lists.llvm.org
Fri Sep 15 15:17:00 PDT 2023


================
@@ -37,9 +37,10 @@ struct __fn {
     _LIBCPP_ASSERT_UNCATEGORIZED(!bool(std::invoke(__comp, std::invoke(__proj, __high), std::invoke(__proj, __low))),
                                  "Bad bounds passed to std::ranges::clamp");
 
-    if (std::invoke(__comp, std::invoke(__proj, __value), std::invoke(__proj, __low)))
+    auto&& __projected = std::invoke(__proj, __value);
----------------
EricWF wrote:

That's not quite true. It will lifetime extend any _value_ returned from that function. However if the function returns a reference to a temporary created in the call to the projection, then that reference will dangle once at the semicolon.

For example, consider the identity projection that tries to prevent copies:

```
std::string const& identity_proj(std::string const& x) { return x; }
```
No matter what,  the return value ends its lifetime when the argument does. If you pass something other than `std::string` to that function, you're in trouble. 

Now, it may be the case that any such code is buggy. I'm not 100% convinced it is. I haven't found standardese that clarifies the situation. But it would work today, and we could continue to make it work my forwarding the projected values down to another function which uses them.




https://github.com/llvm/llvm-project/pull/66315


More information about the cfe-commits mailing list