void doStuff( std::string const & s1, std::string const & s2="");
s2 文字列について、このコードが C++ で合法であるかどうか疑問に思っていました。デフォルトの引数が必要ですが、参照を渡し、空の文字列をデフォルトとして持っています。テンポラリーが作成され、参照はそのテンポラリーを指しますか、それとも違法な C++ ですか?
void doStuff( std::string const & s1, std::string const & s2="");
s2 文字列について、このコードが C++ で合法であるかどうか疑問に思っていました。デフォルトの引数が必要ですが、参照を渡し、空の文字列をデフォルトとして持っています。テンポラリーが作成され、参照はそのテンポラリーを指しますか、それとも違法な C++ ですか?
より良いでしょう
void doStuff( std::string const & s1, std::string const & s2 = std::string());
余分な一時を避けるためconst char *
。(あなたのバリアントには 2 つの一時的なものがあります: aconst char *
と empty std::string
)。
または、ユーザー定義のリテラルを使用する (C++14):
void doStuff( std::string const & s1, std::string const & s2 = ""s);
セマンティックを理解するには、元のステートメントメネットを分割することをお勧めします。
void doStuff( std::string const & s1, std::string const & s2="");
2つのステートメントに
void doStuff( std::string const & s1, std::string const & s2);
doStuff( SomeString, "" );
関数の呼び出しで、2 番目の引数は暗黙的に std::string 型のオブジェクトに変換されます。
s2 = std::string( "" );
したがって、実際には関数の本体に
std::string const &s2 = std::string( "" );
つまり、定数参照 s2 は一時オブジェクト std::string( "" ) を参照します。