Rationale behind member function swap

后端 未结 1 1712
陌清茗
陌清茗 2021-01-27 13:09

In the standard library, if a class type has a specialized swap algorithm, then it will have a member function swap and a free function swap that simpl

相关标签:
1条回答
  • 2021-01-27 13:37

    The free function cannot see the private guts of the class, so the actual functionality needs to be provided as a class member. However, you want the free function because it's a customization point (using ADL); so a generic algorithm will call the free swap in order to achieve whatever swapping is appropriate for the type at hand.

    The member function is also useful for constructions like T().swap(existing_thing), since the free function requires lvalue arguments.

    I suppose the alternative would have been to make swap a public friend function declared inside the class, which could be found via ADL just as well.

    0 讨论(0)
提交回复
热议问题