mercredi 21 avril 2021

The best practice to define global const variables in C++11 [closed]

There are quite a few similar questions asked on the Stackoverflow. However, none of these gave a convincing reasoning about which is better. So my question is what is the best practice to define global const variables in c++11?

To list out a couple options:

  1. static const in a util class
// util.h
class Util {
  static const int i;
  static const string s;
};

// util.cc
const int Util::i = 10;
const string Util::s = "string";
  1. extern const in namespace scope
// util.h
namespace util {
  extern const int i;
  extern const string s;
}

// util.cc
namespace util {
  const int i = 10;
  const string s = "hello";
}

Above 2 solutions have a same problem of the initialization order fiasco. If later people want to use these variable to initialize some other global variables, this need to handled.

  • Use a wrapper function as an accessor and make the global variable a function static variable. This requires to change all places accessing this variable.
  • Change the const to constexpr. This works fine with literal types, but types with non-trivial destructor (e.g. string).
  1. const in namespace scope (internal linkage)
// util.h
namespace util {
  const int i = 10;
  const string s = "string";
}

This will make a copy in each translation unit.

Can someone please give any suggestion regarding what is the best practice I should follow?

Aucun commentaire:

Enregistrer un commentaire