A common pattern I use is:
const string& GetConstString() {
static const auto* my_string = new string("useful const string");
return *my_string;
}
[This is not a leak! See this video]
This resolves many lifetime issues. string
can be replaced with any type with a nontrivial dtor.
If you had a type with a default ctor & trivial dtor, you could simply do
const MyType& GetConstMyType() {
static MyType my_type;
return my_type;
}
I was working with a class that has a default ctor and trivial dtor. And I wondered whether that class would be default- or value- initialized. It turns out, it doesn't really matter for class-types. So this becomes an academic question [eg if you had an array of this class].
But would it be default- or value- initialized?