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

12,294

Solution 1

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

Solution 2

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

Solution 3

Static members of the class.

If they are used in multiple places by the one class, it's usually easier to keep things organized - and to later find where you defined everything - if you keep them defined in the class that uses them. Defining them in-place makes them hard to locate and later modify. And I'd opt for the specific class over the anonymous namespace for cleaner class definition and use.

Solution 4

If the strings are meant to be seen by users of the class, put them into the class. Otherwise, hide them in the implementation file's unnamed namespace.

Share:
12,294
stone
Author by

stone

Updated on June 14, 2022

Comments

  • stone
    stone almost 2 years

    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.