Good evening. I noticed that std::vector has some requirements regarding copy and move assignment operator. I'm trying to implement them using (std::allocator_traits<Allocator>::propagate_on_container_move_assignment::value
.
Is the way I implemented it so far correct?
constexpr vector& operator=(vector&& other) noexcept
{
if (this != &other)
{
if constexpr (std::allocator_traits<Allocator>::propagate_on_container_move_assignment::value)
{
destruct(m_size);
deallocate(m_capacity);
m_allocator = std::move(other.m_allocator);
m_vector = other.m_vector;
}
else if (m_allocator == other.m_allocator)
{
destruct(m_size);
deallocate(m_capacity);
m_vector = other.m_vector;
}
else
{
destruct(m_size);
deallocate(m_capacity);
allocate(other.m_capacity);
std::uninitialized_move(other.m_vector, other.m_vector + other.m_size, m_vector);
}
m_size = other.m_size;
m_capacity = other.m_capacity;
reset(other);
}
return *this;
}
destruct(m_size) = uses std::allocator_traits::destroy within a loop to destruct anything that has been constructed,
deallocate(m_capacity) = uses std::allocator_traits<Allocator::deallocate to deallocate the memory;
m_allocator = It's of type Allocator, which is the allocator passed to the template and by default std::allocator
reset(other) = Leaves the other vector in a good state (m_vector nullptr, capacity & size = 0)
question from:
https://stackoverflow.com/questions/65600682/how-to-use-propagate-on-container-copy-move-assignmentvalue 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…