This is not really a question of safety as much as it is a question of semantics. Nothing prevents you from doing the exact same thing at compiletime:
constexpr A blub()
{
char str[] = "asdf";
return { str };
}
Since there is no way to ever call this function in a core constant expression, a program that contains code like this is ill-formed, no diagnostic required [dcl.constexpr]/5, which really isn't any better than invoking undefined behavior at runtime…
Compiletime or not, you have to ask yourself the question: Should this struct own a string or refer to an existing string? I would strongly recommend against making your struct own a string in a runtime context and refer to an existing string in a compiletime context, even if you find a way to pull this off in theory. We're talking about completely different semantics here. Completely different semantics should generally better be modeled by different types rather than one type that completeley changes its meaning depending on context…
If you want to make a constexpr struct own a string, you'll currently have to resort to some constexpr string implementation such as, e.g., this one. Since your question is tagged with c++20, note that std::string
will be useable in a constexpr context starting with C++20 [basic.string]. So, in C++20, you will be able to just have the member be an std::string
…