Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

c++ - How to use propagate_on_container_copy/move_assignment::value?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...