[libc++] Improve error message for invalid allocators
authorNikolas Klauser <nikolasklauser@berlin.de>
Wed, 12 Oct 2022 18:24:04 +0000 (20:24 +0200)
committerNikolas Klauser <nikolasklauser@berlin.de>
Sat, 15 Oct 2022 22:37:35 +0000 (00:37 +0200)
Reviewed By: ldionne, #libc

Spies: libcxx-commits, rupprecht

Differential Revision: https://reviews.llvm.org/D135803

libcxx/include/__memory/allocator_traits.h
libcxx/test/libcxx/containers/sequences/vector/invalid_allocator.verify.cpp [new file with mode: 0644]

index 619fe11..6acc14a 100644 (file)
@@ -156,7 +156,8 @@ struct __has_rebind_other<_Tp, _Up, __void_t<typename _Tp::template rebind<_Up>:
 
 template <class _Tp, class _Up, bool = __has_rebind_other<_Tp, _Up>::value>
 struct __allocator_traits_rebind {
-    using type _LIBCPP_NODEBUG = typename _Tp::template rebind<_Up>::other;
+  static_assert(__has_rebind_other<_Tp, _Up>::value, "This allocator has to implement rebind");
+  using type _LIBCPP_NODEBUG = typename _Tp::template rebind<_Up>::other;
 };
 template <template <class, class...> class _Alloc, class _Tp, class ..._Args, class _Up>
 struct __allocator_traits_rebind<_Alloc<_Tp, _Args...>, _Up, true> {
diff --git a/libcxx/test/libcxx/containers/sequences/vector/invalid_allocator.verify.cpp b/libcxx/test/libcxx/containers/sequences/vector/invalid_allocator.verify.cpp
new file mode 100644 (file)
index 0000000..abd33a0
--- /dev/null
@@ -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
+//
+//===----------------------------------------------------------------------===//
+
+// Check that vector diagnoses an allocator which has to implement rebind with an appropriate error message
+
+#include <vector>
+
+class FooAllocator {
+ public:
+  using value_type = int;
+  FooAllocator() = default;
+
+  int* allocate(int num_objects);
+
+  void deallocate(int* ptr, int num_objects);
+
+  bool operator==(const FooAllocator&) const { return true; }
+  bool operator!=(const FooAllocator&) const { return false; }
+};
+
+void func() {
+  std::vector<int, FooAllocator> v; //expected-error-re@*:* {{{{(static_assert|static assertion)}} failed {{.*}}This allocator has to implement rebind}}
+}