私に機能があれば
void x(std::string const& s)
{
...
}
そして、私はそれを x("abc") と呼んでいますが、文字列コンストラクターはメモリを割り当ててデータをコピーしますか?
私に機能があれば
void x(std::string const& s)
{
...
}
そして、私はそれを x("abc") と呼んでいますが、文字列コンストラクターはメモリを割り当ててデータをコピーしますか?
std::string コンストラクターはconst char*
引数付きで呼び出されます
メモリが (動的に) 割り当てられるかどうかはわかりませんが、標準ライブラリの実装に SSO が配置されている可能性があります。つまり、動的割り当てなしで小さな文字列を格納できるということです。
The question is tagged with 'performance', so it's actually a good question IMO.
All compilers I know will allocate a copy of the string on the heap. However, some implementation could make the std::string
type intrinsic into the compiler and optimize the heap allocation when an r-value std::string
is constructed from a string literal.
E.g., this is not the case here, but MSVC is capable of replacing heap allocations with static objects when they are done as part of dynamic initialization of statics, at least in some circumstances.
はい、コンパイラは必要なコードを生成して を作成し、std::string
それを引数としてx
関数に渡します。
キーワードでマークされていない限り、単一の引数を取るコンストラクターはexplicit
、引数の型からオブジェクトのインスタンスに暗黙的に変換するために使用されます。
この例でstd::string
は、引数を取るコンストラクターがあるconst char*
ため、コンパイラーはこれを使用して、文字列リテラルをオブジェクトに暗黙的に変換しstd::string
ます。次に、その新しく作成されたオブジェクトの const 参照が関数に渡されます。
詳細は次のとおりです: C++ での明示的なキーワードの意味は何ですか?