Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do I put constant strings in C++: static class members or anonymous namespaces?

I need to define some constant strings that will be used only by one class. It looks like I have three options:

  1. Embed the strings directly into locations where they are used.

  2. Define them as private static constant members of the class:

    //A.h   class A {   private:      static const std::string f1;      static const std::string f2;      static const std::string f3;   };    //A.cpp   const std::string f1 = "filename1";   const std::string f2 = "filename2";   const std::string f3 = "filename3";    //strings are used in this file   
  3. Define them in an anonymous namespace in the cpp file:

    //A.cpp   namespace {     const std::string f1 = "filename1";     const std::string f2 = "filename2";     const std::string f3 = "filename3";   }    //strings are used in this file   

Given these options, which one would you recommend and why? Thanks.

like image 836
stone Avatar asked Mar 17 '10 20:03

stone


People also ask

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.

What is static class in c++?

There is no such thing as a static class in C++. The closest approximation is a class that only contains static data members and static methods. Static data members in a class are shared by all the class objects as there is only one copy of them in the memory, regardless of the number of objects of the class.


2 Answers

I'd place them in anonymous namespace in the CPP file. It makes them private to the implementation and at the same moment makes it visible to the non-member functions that are part of implementation (such as operator<<).

like image 50
Kirill V. Lyadvinsky Avatar answered Sep 28 '22 21:09

Kirill V. Lyadvinsky


If they are used only in a single file then there is no need to expose them to the outside world by including them in the header file.

If they are used and will always be used only in a single place then there's really no reason not to just write them as literals where they need to be used.

If they are used in multiple places in the cpp, I would go for the anonymous namespace.

Another option which you don't mention is to define them as static variables inside the cpp. this is somewhat equivalent to the anonymous namespace option and more C-like than C++.

like image 28
shoosh Avatar answered Sep 28 '22 22:09

shoosh