问题描述
我想知道在有非静态等效项时使用静态成员函数是否有任何优势.它会导致更快的执行(因为不必关心所有成员变量),还是可能减少内存使用(因为没有包含在所有实例中)?
I was wondering whether there's any advantages to using a static member function when there is a non-static equivalent. Will it result in faster execution (because of not having to care about all of the member variables), or maybe less use of memory (because of not being included in all instances)?
基本上,我正在查看的函数是一个实用函数,用于将表示像素颜色的整数数组围绕任意中心点旋转任意度数.它被放置在我的抽象 Bullet 基类中,因为只有子弹会使用它,而且我不希望在某些实用程序类中调用它的开销.它有点太长并且在每个派生的项目符号类中都使用过,因此内联可能不是一个好主意.你建议我如何定义这个函数?作为 Bullet 的静态成员函数,作为 Bullet 的非静态成员函数,或者可能不是作为 Bullet 的成员但在 Bullet.h 的类之外定义?各自的优缺点是什么?
Basically, the function I'm looking at is an utility function to rotate an integer array representing pixel colours an arbitrary number of degrees around an arbitrary centre point. It is placed in my abstract Bullet base class, since only the bullets will be using it and I didn't want the overhead of calling it in some utility class. It's a bit too long and used in every single derived bullet class, making it probably not a good idea to inline. How would you suggest I define this function? As a static member function of Bullet, of a non-static member function of Bullet, or maybe not as a member of Bullet but defined outside of the class in Bullet.h? What are the advantages and disadvantages of each?
推荐答案
静态成员函数和自由函数之间绝对没有性能差异.
There is absolutely no performance difference between static member functions and free functions.
从设计的角度来看,听起来有问题的功能与 Bullets 关系不大,所以我更愿意将它放在某个实用程序库中,这样做没有运行时开销,如果您需要额外的开发人员工作还没有这样的图书馆.
From a design perspective, it sounds like the function in question has very little to do with Bullets, so I would favour putting it in a utility library somewhere, there is no runtime overhead in doing this, only extra developer effort if you don't already have such a library.
关于最初的问题,如果函数显然不属于特定类,那么它应该是一个自由函数.它最多应该属于一个命名空间,以控制其范围.即使它与一个类有关,在大多数情况下,我仍然更喜欢自由函数,除非该函数需要访问私有成员.
Regarding the original question, if the function doesn't obviously pertain to a particular class, then it should be a free function. At the most, it should belong to a namespace, to control its scope. And even if it pertains to a class, most times, I would still prefer the free function unless the function requires access to private members.
这篇关于使用静态成员函数代替等效的非静态成员函数的优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!