When would one use unnamed namespace in C++ ? Is it better in any sense than a free standing function? Also, should it be used only in source file and not in header file?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
According to Stroustrup, you should use it in places where in old C you would have made
staticglobals. The idea is that the items in question can be “global” to the source file they are in, but not pollute the namespace of any other source files in your compilation.In other words, you shouldn’t be creating
staticglobals in C++. You should be using unnamed namespaces instead.I have found some situations where they are useful in header files, but that should be rare. Mostly I think for declaring throwable exceptions. In that case the definitions in question will be global for everything that
#includes that header, but not for things that don’t.