libstdc++: Make INVOKE<R> refuse to create dangling references [PR70692]
authorJonathan Wakely <jwakely@redhat.com>
Tue, 27 Sep 2022 19:59:05 +0000 (20:59 +0100)
committerJonathan Wakely <jwakely@redhat.com>
Wed, 28 Sep 2022 23:33:36 +0000 (00:33 +0100)
This is the next part of the library changes from P2255R2. This makes
INVOKE<R> ill-formed if converting the INVOKE expression to R would bind
a reference to a temporary object.

The is_invocable_r trait is now false if the invocation would create a
dangling reference. This is done by adding the dangling check to the
__is_invocable_impl partial specialization used for INVOKE<R>
expressions. This change also slightly simplifies the nothrow checking
recently added to that partial specialization.

This change also removes the is_invocable_r checks from the pre-C++17
implementation of std::__invoke_r, because there is no need for it to be
SFINAE-friendly. None of our C++11 and C++14 uses of INVOKE<R> require
those constraints. The std::function constructor needs to check
is_invocable_r, but that's already done explicitly, so we don't need to
recheck when calling __is_invoke_r in std::function::operator(). The
other uses of std::__is_invoke_r do not need to be constrained and can
just be ill-formed if the INVOKE<R> expression is ill-formed.

libstdc++-v3/ChangeLog:

PR libstdc++/70692
* include/bits/invoke.h [__cplusplus < 201703] (__invoke_r):
Remove is_invocable and is_convertible constraints.
* include/std/type_traits (__is_invocable_impl::_S_conv): Use
non-deduced context for parameter.
(__is_invocable_impl::_S_test): Remove _Check_noex template
parameter and use deduced noexcept value in its place. Add bool
parameter to detect dangling references.
(__is_invocable_impl::type): Adjust call to _S_test to avoid
deducing unnecessary noexcept property..
(__is_invocable_impl::__nothrow_type): Rename to ...
(__is_invocable_impl::__nothrow_conv): ... this. Adjust call
to _S_test to deduce noexcept property.
* testsuite/20_util/bind/dangling_ref.cc: New test.
* testsuite/20_util/function/cons/70692.cc: New test.
* testsuite/20_util/function_objects/invoke/dangling_ref.cc:
New test.
* testsuite/20_util/is_invocable/dangling_ref.cc: New test.
* testsuite/30_threads/packaged_task/cons/dangling_ref.cc:
New test.

libstdc++-v3/include/bits/invoke.h
libstdc++-v3/include/std/type_traits
libstdc++-v3/testsuite/20_util/bind/dangling_ref.cc [new file with mode: 0644]
libstdc++-v3/testsuite/20_util/function/cons/70692.cc [new file with mode: 0644]
libstdc++-v3/testsuite/20_util/function_objects/invoke/dangling_ref.cc [new file with mode: 0644]
libstdc++-v3/testsuite/20_util/is_invocable/dangling_ref.cc [new file with mode: 0644]
libstdc++-v3/testsuite/30_threads/packaged_task/cons/dangling_ref.cc [new file with mode: 0644]

index cdecca0..8724a76 100644 (file)
@@ -115,29 +115,23 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
                                          std::forward<_Callable>(__fn),
                                          std::forward<_Args>(__args)...);
     }
-#else // C++11
-  template<typename _Res, typename _Callable, typename... _Args>
-    using __can_invoke_as_void = __enable_if_t<
-      __and_<is_void<_Res>, __is_invocable<_Callable, _Args...>>::value,
-      _Res
-    >;
-
-  template<typename _Res, typename _Callable, typename... _Args>
-    using __can_invoke_as_nonvoid = __enable_if_t<
-      __and_<__not_<is_void<_Res>>,
-            is_convertible<typename __invoke_result<_Callable, _Args...>::type,
-                           _Res>
-      >::value,
-      _Res
-    >;
+#else // C++11 or C++14
+  // This is a non-SFINAE-friendly std::invoke_r<R>(fn, args...) for C++11/14.
+  // It's used in std::function, std::bind, and std::packaged_task. Only
+  // std::function is constrained on is_invocable_r, but that is checked on
+  // construction so doesn't need to be checked again when calling __invoke_r.
+  // Consequently, these __invoke_r overloads do not check for invocable
+  // arguments, nor check that the invoke result is convertible to R.
 
   // INVOKE<R>: Invoke a callable object and convert the result to R.
   template<typename _Res, typename _Callable, typename... _Args>
-    constexpr __can_invoke_as_nonvoid<_Res, _Callable, _Args...>
+    constexpr __enable_if_t<!is_void<_Res>::value, _Res>
     __invoke_r(_Callable&& __fn, _Args&&... __args)
     {
       using __result = __invoke_result<_Callable, _Args...>;
       using __type = typename __result::type;
+      static_assert(!__reference_converts_from_temporary(_Res, __type),
+                   "INVOKE<R> must not create a dangling reference");
       using __tag = typename __result::__invoke_type;
       return std::__invoke_impl<__type>(__tag{}, std::forward<_Callable>(__fn),
                                        std::forward<_Args>(__args)...);
@@ -145,7 +139,7 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
 
   // INVOKE<R> when R is cv void
   template<typename _Res, typename _Callable, typename... _Args>
-    _GLIBCXX14_CONSTEXPR __can_invoke_as_void<_Res, _Callable, _Args...>
+    _GLIBCXX14_CONSTEXPR __enable_if_t<is_void<_Res>::value, _Res>
     __invoke_r(_Callable&& __fn, _Args&&... __args)
     {
       using __result = __invoke_result<_Callable, _Args...>;
@@ -154,7 +148,7 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
       std::__invoke_impl<__type>(__tag{}, std::forward<_Callable>(__fn),
                                 std::forward<_Args>(__args)...);
     }
-#endif // C++11
+#endif // C++11 or C++14
 
 _GLIBCXX_END_NAMESPACE_VERSION
 } // namespace std
index 1ac8051..22c1af2 100644 (file)
@@ -2864,7 +2864,7 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
     struct __is_invocable_impl
     : false_type
     {
-      using __nothrow_type = false_type; // For is_nothrow_invocable_r
+      using __nothrow_conv = false_type; // For is_nothrow_invocable_r
     };
 
   // Used for valid INVOKE and INVOKE<void> expressions.
@@ -2874,7 +2874,7 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
                               __void_t<typename _Result::type>>
     : true_type
     {
-      using __nothrow_type = true_type; // For is_nothrow_invocable_r
+      using __nothrow_conv = true_type; // For is_nothrow_invocable_r
     };
 
 #pragma GCC diagnostic push
@@ -2887,18 +2887,22 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
     {
     private:
       // The type of the INVOKE expression.
+      using _Res_t = typename _Result::type;
+
       // Unlike declval, this doesn't add_rvalue_reference, so it respects
       // guaranteed copy elision.
-      static typename _Result::type _S_get() noexcept;
+      static _Res_t _S_get() noexcept;
 
+      // Used to check if _Res_t can implicitly convert to _Tp.
       template<typename _Tp>
-       static void _S_conv(_Tp) noexcept;
+       static void _S_conv(__type_identity_t<_Tp>) noexcept;
 
       // This overload is viable if INVOKE(f, args...) can convert to _Tp.
-      template<typename _Tp, bool _Check_Noex = false,
+      template<typename _Tp,
+              bool _Nothrow = noexcept(_S_conv<_Tp>(_S_get())),
               typename = decltype(_S_conv<_Tp>(_S_get())),
-              bool _Noex = noexcept(_S_conv<_Tp>(_S_get()))>
-       static __bool_constant<_Check_Noex ? _Noex : true>
+              bool _Dangle = __reference_converts_from_temporary(_Tp, _Res_t)>
+       static __bool_constant<_Nothrow && !_Dangle>
        _S_test(int);
 
       template<typename _Tp, bool = false>
@@ -2907,10 +2911,10 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
 
     public:
       // For is_invocable_r
-      using type = decltype(_S_test<_Ret>(1));
+      using type = decltype(_S_test<_Ret, /* Nothrow = */ true>(1));
 
       // For is_nothrow_invocable_r
-      using __nothrow_type = decltype(_S_test<_Ret, true>(1));
+      using __nothrow_conv = decltype(_S_test<_Ret>(1));
     };
 #pragma GCC diagnostic pop
 
@@ -3041,9 +3045,12 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
     };
 
   /// @cond undocumented
+  // This checks that the INVOKE<R> expression is well-formed and that the
+  // conversion to R does not throw. It does *not* check whether the INVOKE
+  // expression itself can throw. That is done by __call_is_nothrow_ instead.
   template<typename _Result, typename _Ret>
     using __is_nt_invocable_impl
-      = typename __is_invocable_impl<_Result, _Ret>::__nothrow_type;
+      = typename __is_invocable_impl<_Result, _Ret>::__nothrow_conv;
   /// @endcond
 
   /// std::is_nothrow_invocable_r
diff --git a/libstdc++-v3/testsuite/20_util/bind/dangling_ref.cc b/libstdc++-v3/testsuite/20_util/bind/dangling_ref.cc
new file mode 100644 (file)
index 0000000..70393e4
--- /dev/null
@@ -0,0 +1,9 @@
+// { dg-do compile { target c++11 } }
+#include <functional>
+
+int f();
+auto b = std::bind<const int&>(f);
+int i = b(); // { dg-error "here" "" { target { c++14_down } } }
+// { dg-error "dangling reference" "" { target { c++14_down } } 0 }
+// { dg-error "no matching function" "" { target c++17 } 0 }
+// { dg-error "enable_if" "" { target c++17 } 0 }
diff --git a/libstdc++-v3/testsuite/20_util/function/cons/70692.cc b/libstdc++-v3/testsuite/20_util/function/cons/70692.cc
new file mode 100644 (file)
index 0000000..7cdc472
--- /dev/null
@@ -0,0 +1,13 @@
+// { dg-do compile { target c++11 } }
+// PR libstdc++/70692
+// No warning when function<const int&(...)> binds a reference to a temporary
+#include <functional>
+
+int f();
+
+int main()
+{
+  std::function<const int&()> ff(f);  // { dg-error "no matching function" }
+  std::function<long&&()> f2(f);      // { dg-error "no matching function" }
+}
+// { dg-error "std::enable_if" "" { target *-*-* } 0 }
diff --git a/libstdc++-v3/testsuite/20_util/function_objects/invoke/dangling_ref.cc b/libstdc++-v3/testsuite/20_util/function_objects/invoke/dangling_ref.cc
new file mode 100644 (file)
index 0000000..1513480
--- /dev/null
@@ -0,0 +1,12 @@
+// { dg-options "-std=gnu++23" }
+// { dg-do compile { target c++23 } }
+#include <functional>
+
+int f();
+
+template<typename R>
+concept can_invoke = requires (int (&f)()) { std::invoke_r<R>(f); };
+
+static_assert( not can_invoke<const int&> );
+static_assert( not can_invoke<int&&> );
+static_assert( not can_invoke<const long&> );
diff --git a/libstdc++-v3/testsuite/20_util/is_invocable/dangling_ref.cc b/libstdc++-v3/testsuite/20_util/is_invocable/dangling_ref.cc
new file mode 100644 (file)
index 0000000..46719b9
--- /dev/null
@@ -0,0 +1,6 @@
+// { dg-do compile { target c++17 } }
+#include <type_traits>
+
+static_assert( not std::is_invocable_r_v<const int&, int()> );
+static_assert( not std::is_invocable_r_v<int&&, int()> );
+static_assert( not std::is_invocable_r_v<const long&, int()> );
diff --git a/libstdc++-v3/testsuite/30_threads/packaged_task/cons/dangling_ref.cc b/libstdc++-v3/testsuite/30_threads/packaged_task/cons/dangling_ref.cc
new file mode 100644 (file)
index 0000000..e9edb5e
--- /dev/null
@@ -0,0 +1,11 @@
+// { dg-do compile { target c++11 } }
+#include <future>
+
+// C++20 [futures.task.members]
+// Mandates: is_invocable_r_v<R, F&, ArgTypes...> is true.
+
+int f();
+std::packaged_task<const int&()> task(f);
+// { dg-error "dangling reference" "" { target { c++14_down } } 0 }
+// { dg-error "no matching function" "" { target c++17 } 0 }
+// { dg-error "enable_if" "" { target c++17 } 0 }