Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static class data vs. anonymous namespaces in C++

I occasionally have classes with private static data members. I'm currently debating if I should replace these with static variables in an unnamed namespace in the implementation file. Other that not being able to use these variables in inline methods, are there any other drawbacks? The advantage that I see is that is hides them completely from the users of the class.

like image 712
KeithB Avatar asked May 13 '09 13:05

KeithB


People also ask

Can a namespace be private?

An object namespace protects named objects from unauthorized access. Creating a private namespace enables applications and services to build a more secure environment. A process can create a private namespace using the CreatePrivateNamespace function.

What is the point of anonymous namespaces?

An anonymous namespace makes the enclosed variables, functions, classes, etc. available only inside that file. In your example it's a way to avoid global variables. There is no runtime or compile time performance difference.

What is unnamed namespace in C++?

A namespace with no identifier before an opening brace produces an unnamed namespace. Each translation unit may contain its own unique unnamed namespace.

Are namespace variables static?

By default, an object or variable that is defined in the global namespace has static duration and external linkage. The static keyword can be used in the following situations.


1 Answers

I'm not convinced that the benefit is worth the readability impact. I generally consider something that's private to be "hidden enough."

like image 57
Greg D Avatar answered Sep 19 '22 00:09

Greg D