次の点を考慮してください。
class Foo {
public:
Foo (const char *in) {
printf ("C string constructor called\n");
}
Foo (std::string const &in) : Foo(in.c_str()) {
printf ("C++ string constructor called\n");
}
};
Foo bar ("I never asked for this");
//C string constructor called
したがって、定数string
は 1 として扱われconst char *
ます。
std::string
しかし、コンストラクターを「プライマリ」にすると何が変わるでしょうか?
std::string
C 文字列関連のオブジェクトを呼び出さずに、オブジェクトが作成され、対応するコンストラクターに渡されると期待できますか?
class Foo {
public:
Foo (std::string const &in) {
printf ("C++ string constructor called\n");
}
Foo (const char *in) : Foo(std::string (in)) {
printf ("C string constructor called\n");
}
};
Foo bar ("I never asked for this");
//C++ string constructor called
//C string constructor called
繰り返しますが、C 文字列コンストラクターが最初に呼び出されました。
この動作は C++ 標準で説明されていますか、それともコンパイラ関連ですか?
これは、テンプレートやオーバーロードされた関数などでも同じように機能しますか?
GCC 7.3.0 (MSYS2 x64) でコンパイルしました。