成员函数交换背后的原理 [英] Rationale behind member function swap

查看:67
本文介绍了成员函数交换背后的原理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在标准库中,如果类类型具有专用的交换算法,则它将具有成员函数swap和自由函数swap,该函数简单地转发到成员函数.我并没有完全理解拥有这两者的理由(因此也有代码重复),而不仅仅是自由功能之一.注意,当我说自由函数时,我指的是专门的自由交换函数,而不是通用的std::swap函数模板.这样的专门功能可以通过成为相关类的朋友来特权访问相关类.

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 simply forwards to the member function. I don't quite get the rationale behind having both of them (and thus code duplication) but not just the free function one. Note that, when I say the free function, I take to mean the specialized free swap function, not the generic std::swap function template. Such a specialized function may have privileged access to the relevant class by being a friend of it.

我有两点可以支持只保留free函数而不是成员函数.首先,它形成了一个更通用的交换接口,以方便编写通用算法,因为像数组这样的非类类型不能具有成员函数.其次,交换是涉及两个操作数的二进制运算,并显示出一种对称感.使用自由函数执行交换是更自然和直观的,该自由函数对任何一个操作数都没有偏倚.因此,使用成员函数swap时总是感到有些奇怪,好像我正在执行基于调用对象的某些操作一样.

I have two points to support just leaving the free function rather than the member function. First, it forms a more generic swap interface to facilitate writing generic algorithms, for non-class types like arrays cannot have member functions. Second, swap is a binary operation involving two operands and demonstrates a sense of symmetry. It's more natural and intuitive to perform swap using a free function that does not have bias on either operand. For this reason, I have always felt somewhat weird when using the member function swap as if I was performing some operation that is based on the invoking object.

推荐答案

free函数无法看到类的私有内容,因此实际功能需要作为类成员提供.但是,您需要free函数,因为它是一个自定义点(使用ADL);因此,通用算法将调用免费的swap,以实现适合手头类型的任何交换.

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.

成员函数对于像T().swap(existing_thing)这样的结构也很有用,因为自由函数需要左值参数.

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

我想替代方法是使swap是在类内部声明的公共朋友函数,也可以通过ADL找到该函数.

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.

这篇关于成员函数交换背后的原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆