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

stone picture stone · Mar 17, 2010 · Viewed 12.1k times · Source

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.

Answer

Kirill V. Lyadvinsky picture Kirill V. Lyadvinsky · Mar 17, 2010

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<<).