在C++类中,使用静态函数而不是成员函数会产生任何开销.
class CExample
{
public:
int foo( int a, int b) {
return a + b ;
}
static int bar( int a, int b) {
return a + b ;
}
};
Run Code Online (Sandbox Code Playgroud)
我的问题是;
在这个例子中foo()或bar()更有效率?
不.两个电话都是静态解决的.将this指针传递给非static函数可能会有一些开销,但在这种情况下,两者都可能被内联.
为什么我不想让foo()进入静态函数,因为它不会改变任何成员变量?
你不会,实际上很好的做法是让所有方法都不绑定到实例static.
本回答重点讨论了您的问题的第二部分
引用C++编码标准:101规则,指南和最佳实践:
第44章.更喜欢编写非成员非友好函数
[...] 非成员非友好函数通过最小化依赖性来改进封装[...]
Scott Meyers提出了以下算法来确定哪些方法应该是类的成员(源)
if (f needs to be virtual)
make f a member function of C;
else if (f is operator>> or operator<<)
{
make f a non-member function;
if (f needs access to non-public members of C)
make f a friend of C;
}
else if (f needs type conversions on its left-most argument)
{
make f a non-member function;
if (f needs access to non-public members of C)
make f a friend of C;
}
else if (f can be implemented via C's public interface)
make f a non-member function;
else
make f a member function of C;
Run Code Online (Sandbox Code Playgroud)
至于问题的前半部分,我猜测编译器会优化任何差异.