Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

c++ - private static member function or free function in anonymous namespace?

I've recently made a change stylistically and wanted to see how other c++ programmers felt about it and if there were any downsides to it.

Essentially, when I needed a utility function which doesn't need access to a given class member, what I used to do was something like this:

file.h

class A {
public:
    // public interface
private:
    static int some_function(int);
};

file.cpp

int A::some_function(int) {
    // ...
}

But more recently, I have been preferring to do something more like this:

file.cpp

namespace {
    int some_function(int) {

    }
}
// the rest of file.cpp

Here's my thought process:

  • it's one less file the edit
  • simply having the function be listed in the header file can hint at implementation details which have no need to be exposed (even if not publically available).
  • if the prototype of the function needs to change, only one file needs to be recompiled.

The last one is the most compelling to me. So my question is: are there any downsides to this?

They are functionally equivalent for most purposes that I can think of. It kind of seems to me that a private static function can almost always be converted to a free function in an anonymous namespace.

EDIT: One thing that comes to mind is that a private static function would have access to private members if given a pointer to an object to operate on, but if that's the case, why not make it a non-static member?

What do you guys think?

question from:https://stackoverflow.com/questions/6598244/private-static-member-function-or-free-function-in-anonymous-namespace

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the function is only used in one source file, it makes perfect sense to define it there. If nobody else is using it, it doesn't belong in the header.

As you say, it reduces dependencies and can potentially save some recompiles.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...