30

What is the advantage of having a free function (in anonymous namespace and accessible only in a single source file) and sending all variables as parameters as opposed to having a private class member function free of any parameters and accessing member variables directly?

header:

 Class A {
    int myVariable;
    void DoSomething() {
       myVariable = 1;
    }
 };

source:

 namespace {
    void DoSomething2(int &a) {
        a = 1;
    }
 }

 int A::SomeFunction() {
    DoSomething2(myVariable); // calling free function
    DoSomething(); // calling member function
 }

If you prefer making them members, then what if I have a case where I first call a function that is not accessing any member variables, but that function calls another function which is accessing a member. Should they both be member functions or free?

4

3 回答 3

25

看到这个问题:Effective C++ Item 23 Prefer non-member non-friend functions to member functions and also C++ Member Functions vs Free Functions

你应该更喜欢自由函数,因为它促进了松散耦合。

仅当它适用于您的课程并且您认为它确实与您的课程相关时,才考虑将其设为成员函数。

这是101 C++ 编码标准一书中的一个要点,它指出自由函数和静态函数优于成员函数。

尽管这可能被认为是基于意见的,但它允许保持课堂很少,并分离关注点。

这个答案指出:“这条规则的原因是,通过使用成员函数,您可能会意外地过度依赖类的内部结构。”

于 2014-01-09T19:02:23.920 回答
14

源文件中非成员函数的一个优点类似于Pimpl idiom的优点:如果您更改实现,使用您的标头的客户端不必重新编译。

// widget.h
class Widget 
{
public:
    void meh();
private:
    int bla_;
};

// widget.cpp
namespace {
    void helper(Widget* w) // clients will never know about this
    { /* yadayada */ }
}

void widget::meh() 
{ helper(this); }

当然,这样写的时候,helper()只能使用公共接口Widget,所以收获不大。您可以为insidefriend声明,但在某些时候您最好切换到成熟的 Pimpl 解决方案。helper()Widget

于 2014-01-09T19:03:32.173 回答
8

自由函数与成员函数的主要优势在于它有助于将接口与实现分离。例如,std::sort不需要知道它所操作的底层容器的任何信息,只需知道它可以访问提供某些特性的容器(通过迭代器)。

在您的示例中,该DoSomething2方法对减少耦合没有太大作用,因为它仍然必须通过引用传递来访问私有成员。几乎可以肯定的是,只在普通DoSomething方法中进行状态突变会更明显。

当您可以根据类的公共接口实现任务或算法时,这将使其成为创建自由函数的良好候选者。Scott Meyers 在这里总结了一套合理的规则:http: //cpptips.com/nmemfunc_encap

于 2014-01-10T18:24:36.723 回答