3

How to define static const std::string class variable which can be used everywhere in my program safely?

1st approach - fails static initialization order fiasco:

file: Consts.h

namespace constants {
    struct Consts {
        static const std::string kVar = "123";
    }
}

2nd approach - leads to copying kVar into every translation unit we are including this header to, which leads to One Definition Rule violation principle and may cause double free or use after free errors - this is undefined behaviour if this definition is included into multiple cpp files (which I want to do because I want global shared std::string const).

file: Consts.h

namespace constants {
   const std::string kVar = "123";
}

Is there better way (except using macros - which is global so ugly solution as well) to define such var in safe way? What are the best proven practises to such constructs?

1 Answer 1

5

The common way is to declare the static const variable in the header file but to define it in a cpp file with proper initialization:

.h file:

namespace constants {
    struct Consts {
        static const std::string kVar;
    }
}

.cpp file:

const std::string constants::Consts::kVar = "123";

one more thing, the namespace "constants" already imply constants.. no need to nest inner class named "Consts" .. loose the "Consts" and use only the namespace with the same technique.

Sign up to request clarification or add additional context in comments.

1 Comment

I've used namespace constants just to illustrate an example that there is some namespace here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.