When are constexpr objects constructed?

Viewed 2905

When are constexpr objects constructed relative to non-constexpr non-local objects with static storage duration? Do they start their life prior to initialization of any other objects, i.e., prior to dynamic initialization?

I'm contemplating whether it would be reasonable to have a string_literal class (live example) which is used, e.g., to compare std::strings against certain keywords:

class string_literal
{
    // private members
public:
    constexpr string_literal(char const* b);
    bool operator== (std::string const& other) const;
    bool operator!= (std::string const& other) const;
    // other member functions
};

constexpr string_literal hello("hello");
void f(std::string const& s) {
    if (s == hello) {
        // do something
    }
}

Since the string_literal could parse the string-literal at compile-time to locate the first null-character, I could imagine that these comparisons can be made faster than comparing a std::string against a string-literal. However, to be safe it is necessary that the hello object is readily constructed when the first constructor is executed at run-time during static initialization: otherwise these objects could be accidentally accessed when they are not, yet, constructed.

1 Answers
Related