开发者

Where to store Class Specific named constants in C++

开发者 https://www.devze.com 2023-01-08 01:03 出处:网络
If you have a class that has some named constants, what is the best practive for storing the constants:

If you have a class that has some named constants, what is the best practive for storing the constants:

Option 1: Namespace in Class header

So in my class header I will have:

class myClass
{
...
...
};

namespace NamedConstants
{
   const string Bucket = "Bucket";
}

Option 2 Member Constants

class MyClass {      // this goes in the class
private:                          // header file
  static const string Bucket;
  ...
};

... and in the class implementation file:

const string MyCla开发者_StackOverflow中文版ss::Bucket = "Bucket";

I actually prefer Option 1, considering it to be cleaner: the variable name and value appear together. Also, if you give the namespace a good name then it can make code more readable when you use constants:

TrafficLight::Green

Does anybody see any issue with this method over Option 2?


If the strings are meant to be seen/used by users of the class, you wouldn't consider to make them private class members. So I conclude they are not meant to be seen/used by users of the class. But then it doesn't make sense to put them into the header at all.

If you put them into the class (or into namespace scope into the header), then all changes to their type and identifier will force clients to recompile their code.

If you put them into the class' implementation file, they are a private detail of the class' implementation and changes to them only force recompilation of the class' implementation.
If you put them into an unnamed namespace, they cannot collide with any other name:

namespace  {
  namespace NamedConstants
  {
     const string Bucket = "Bucket";
  }
}


Option 1 could lead to a separate string object for every file which includes the header. So it depends among others on how scarce your resources are.

0

精彩评论

暂无评论...
验证码 换一张
取 消