[libcxx-commits] [PATCH] D116380: [libc++] Use std::addressof in std::function::target

Louis Dionne via Phabricator via libcxx-commits libcxx-commits at lists.llvm.org
Wed Dec 29 09:25:52 PST 2021


ldionne created this revision.
ldionne requested review of this revision.
Herald added a project: libc++.
Herald added a subscriber: libcxx-commits.
Herald added a reviewer: libc++.

This guards against hostile overloads of operator&. Thanks to Peter Dimov
for the report.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116380

Files:
  libcxx/include/__functional/function.h
  libcxx/test/std/utilities/function.objects/func.wrap/func.wrap.func/addressof.pass.cpp


Index: libcxx/test/std/utilities/function.objects/func.wrap/func.wrap.func/addressof.pass.cpp
===================================================================
--- /dev/null
+++ libcxx/test/std/utilities/function.objects/func.wrap/func.wrap.func/addressof.pass.cpp
@@ -0,0 +1,28 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+// <functional>
+
+// class function<R(ArgTypes...)>
+
+// Make sure we can use std::function with a type that has a hostile overload
+// of operator&().
+
+#include <functional>
+#include <cassert>
+
+struct TrapAddressof {
+    void operator&() const; // badly behaved addressof operator
+    int operator()() const { return 1; }
+};
+
+int main(int, char**) {
+    std::function<int()> f(TrapAddressof{});
+    assert(f() == 1);
+    return 0;
+}
Index: libcxx/include/__functional/function.h
===================================================================
--- libcxx/include/__functional/function.h
+++ libcxx/include/__functional/function.h
@@ -16,6 +16,7 @@
 #include <__functional/invoke.h>
 #include <__functional/unary_function.h>
 #include <__iterator/iterator_traits.h>
+#include <__memory/addressof.h>
 #include <__memory/allocator_traits.h>
 #include <__memory/compressed_pair.h>
 #include <__memory/shared_ptr.h>
@@ -360,7 +361,7 @@
 __func<_Fp, _Alloc, _Rp(_ArgTypes...)>::target(const type_info& __ti) const _NOEXCEPT
 {
     if (__ti == typeid(_Fp))
-        return &__f_.__target();
+        return _VSTD::addressof(__f_.__target());
     return nullptr;
 }
 


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D116380.396545.patch
Type: text/x-patch
Size: 1845 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/libcxx-commits/attachments/20211229/c63de8a9/attachment-0001.bin>


More information about the libcxx-commits mailing list