[libc-commits] [libc] [libc] Implement cpp::unique_ptr utility (PR #206701)

Pavel Labath via libc-commits libc-commits at lists.llvm.org
Wed Jul 1 00:53:00 PDT 2026


================
@@ -0,0 +1,214 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Standalone implementation of std::unique_ptr.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC___SUPPORT_CPP_UNIQUE_PTR_H
+#define LLVM_LIBC_SRC___SUPPORT_CPP_UNIQUE_PTR_H
+
+#include "src/__support/CPP/new.h"
+#include "src/__support/CPP/type_traits.h"
+#include "src/__support/CPP/utility.h"
+#include "src/__support/macros/attributes.h"
+#include "src/__support/macros/config.h"
+
+namespace LIBC_NAMESPACE_DECL {
+namespace cpp {
+
+/// A wrapper for deleting objects by default.
+template <typename T> struct default_delete {
+  LIBC_INLINE constexpr default_delete() = default;
+
+  template <typename U, typename = typename enable_if<
+                            is_convertible<U *, T *>::value>::type>
+  LIBC_INLINE constexpr default_delete(const default_delete<U> &) {}
+
+  LIBC_INLINE constexpr void operator()(T *ptr) const {
+    static_assert(sizeof(T) > 0, "cannot delete an incomplete type");
+    delete ptr;
+  }
+};
+
+/// A wrapper for deleting array objects by default.
+template <typename T> struct default_delete<T[]> {
+  LIBC_INLINE constexpr default_delete() = default;
+
+  template <typename U, typename = typename enable_if<
+                            is_convertible<U (*)[], T (*)[]>::value>::type>
+  LIBC_INLINE constexpr default_delete(const default_delete<U[]> &) {}
+
+  template <typename U, typename = typename enable_if<
+                            is_convertible<U (*)[], T (*)[]>::value>::type>
+  LIBC_INLINE constexpr void operator()(U *ptr) const {
+    static_assert(sizeof(U) > 0, "cannot delete an incomplete type");
+    delete[] ptr;
+  }
+};
+
+/// A smart pointer that owns and manages another object through a pointer.
+template <typename T, typename Deleter = default_delete<T>> class unique_ptr {
+  T *ptr_ = nullptr;
+  Deleter deleter_;
----------------
labath wrote:

I see you've mentioned "No empty member optimization" as one of the simplifications. That would certainly make sense if one had to do the empty base class dance to get it. But [[no_unique_address]] is simple enough to be worth it.

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


More information about the libc-commits mailing list