headerファイルに文字列定数(string編)
struct { static const char* foo = (char*)"foo"; }
とても便利なのですが,
class T{ private: U* u_; static const char* foo = (char*)"foo"; public: const string& get_u{return (u_==nullptr)?(foo):(*u_);} };
では使用することができません
かといって,fooをコンストラクタで初期化し続ける実装もナンセンスのような気がします
悩んだ末に,headerファイルだけでstd::stringを定義する場合は
以下のようにするのがbetterのようですた
class T{ private: U* u_; static const string& foo(){ static const string foo_="foo"; return foo_;} public: const string& get_u{return (u_==nullptr)?(foo()):(*u_);} };
constexprでないので,若干runtimeにオーバーヘッドが生じる(と思う)のですが
今の私のC++力では上記が限界でした.