Skip to content

Commit

Permalink
Checking for self assign
Browse files Browse the repository at this point in the history
to avoid potential UB if doing memcpy of buffer to itself
  • Loading branch information
OleErikPeistorpet committed May 8, 2024
1 parent 018da29 commit c4c438e
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions dynarray.h
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,8 @@ class dynarray
dynarray & operator =(dynarray && other) &
noexcept(_alloTrait::propagate_on_container_move_assignment::value or _alloTrait::is_always_equal::value);
//! Requires that allocator_type is always equal or does not have propagate_on_container_copy_assignment
dynarray & operator =(const dynarray & other) &
{
static_assert(!_alloTrait::propagate_on_container_copy_assignment::value or _alloTrait::is_always_equal::value,
"Alloc propagate_on_container_copy_assignment unsupported");
assign(other); return *this;
}
dynarray & operator =(const dynarray & other) &;

dynarray & operator =(std::initializer_list<T> il) & { assign(il); return *this; }

void swap(dynarray & other) noexcept;
Expand Down Expand Up @@ -479,7 +475,6 @@ class dynarray
else
{ _m.end = _m.data + count;
}
// UB for self assign, but found to work. Add check in operator = or use memmove?
_detail::MemcpyCheck(src, count, _m.data);

return src + count;
Expand Down Expand Up @@ -771,6 +766,17 @@ dynarray<T, Alloc> & dynarray<T, Alloc>::operator =(dynarray && other) &
return *this;
}

template< typename T, typename Alloc >
dynarray<T, Alloc> & dynarray<T, Alloc>::operator =(const dynarray & other) &
{
static_assert(!_alloTrait::propagate_on_container_copy_assignment::value or _alloTrait::is_always_equal::value,
"Alloc propagate_on_container_copy_assignment unsupported");
if (this != &other) // avoid memcpy data to itself
assign(other);

return *this;
}

template< typename T, typename Alloc >
dynarray<T, Alloc>::dynarray(size_type n, for_overwrite_t, Alloc a)
: _m(a)
Expand Down

0 comments on commit c4c438e

Please sign in to comment.