Skip to content

Commit

Permalink
cleanup the swap implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
KRM7 committed Feb 7, 2024
1 parent 571c51d commit bc87d05
Showing 1 changed file with 13 additions and 14 deletions.
27 changes: 13 additions & 14 deletions src/small_unique_ptr.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -238,8 +238,6 @@ class small_unique_ptr : private detail::small_unique_ptr_base<T>

constexpr small_unique_ptr& operator=(small_unique_ptr&& other) noexcept
{
if (std::addressof(other) == this) [[unlikely]] return *this;

return operator=<T>(std::move(other));
}

Expand All @@ -248,6 +246,8 @@ class small_unique_ptr : private detail::small_unique_ptr_base<T>
{
static_assert(!detail::is_proper_base_of_v<T, U> || std::has_virtual_destructor_v<T>);

if (std::addressof(other) == this) [[unlikely]] return *this;

if (!other.is_stack_allocated() || std::is_constant_evaluated())
{
reset(std::exchange(other.data_, nullptr));
Expand Down Expand Up @@ -281,14 +281,17 @@ class small_unique_ptr : private detail::small_unique_ptr_base<T>
this->data_ = new_data;
}

constexpr void swap(small_unique_ptr& other) noexcept requires(detail::is_always_heap_allocated_v<T>)
constexpr void swap(small_unique_ptr& other) noexcept
{
std::swap(this->data_, other.data_);
}

constexpr void swap(small_unique_ptr& other) noexcept requires(!detail::is_always_heap_allocated_v<T>)
{
if (is_stack_allocated() && other.is_stack_allocated())
if constexpr (is_always_heap_allocated())
{
std::swap(this->data_, other.data_);
}
else if (!is_stack_allocated() && !other.is_stack_allocated())
{
std::swap(this->data_, other.data_);
}
else if (is_stack_allocated() && other.is_stack_allocated())
{
const std::ptrdiff_t other_offset = other.offsetof_base();
const std::ptrdiff_t this_offset = this->offsetof_base();
Expand All @@ -306,10 +309,6 @@ class small_unique_ptr : private detail::small_unique_ptr_base<T>
this->data_ = this->buffer(other_offset);
other.data_ = other.buffer(this_offset);
}
else if (!is_stack_allocated() && !other.is_stack_allocated())
{
std::swap(this->data_, other.data_);
}
else if (!is_stack_allocated() && other.is_stack_allocated())
{
const pointer new_data = this->buffer(other.offsetof_base());
Expand All @@ -328,7 +327,7 @@ class small_unique_ptr : private detail::small_unique_ptr_base<T>
pointer release() noexcept = delete;

[[nodiscard]]
constexpr static bool is_always_heap_allocated() noexcept
static constexpr bool is_always_heap_allocated() noexcept
{
return detail::is_always_heap_allocated_v<T>;
}
Expand Down

0 comments on commit bc87d05

Please sign in to comment.