Why do some people use swap for move assignments?

后端 未结 4 689
一个人的身影
一个人的身影 2020-11-28 19:53

For example, stdlibc++ has the following:

unique_lock& operator=(unique_lock&& __u)
{
    if(_M_owns)
        unlock();
    unique_lock(std::move         


        
4条回答
  •  Happy的楠姐
    2020-11-28 20:25

    It's about exception safety. Since __u is already constructed when the operator is called, we know there's no exception, and swap doesn't throw.

    If you did the member assignments manually, you'd risk that each of those might throw an exception, and then you'd have to deal with having partially move-assigned something but having to bail out.

    Maybe in this trivial example this doesn't show, but it's a general design principle:

    • Copy-assign by copy-construct and swap.
    • Move-assign by move-construct and swap.
    • Write + in terms of construct and +=, etc.

    Basically, you try to minimize the amount of "real" code and try to express as many other features in terms of the core features as you can.

    (The unique_ptr takes an explicit rvalue reference in the assignment because it does not permit copy construction/assignment, so it's not the best example of this design principle.)

提交回复
热议问题