0

私に機能があれば

void x(std::string const& s)
{
   ...
}

そして、私はそれを x("abc") と呼んでいますが、文字列コンストラクターはメモリを割り当ててデータをコピーしますか?

4

4 に答える 4

4

std::string コンストラクターはconst char*引数付きで呼び出されます

メモリが (動的に) 割り当てられるかどうかはわかりませんが、標準ライブラリの実装に SSO が配置されている可能性があります。つまり、動的割り当てなしで小さな文字列を格納できるということです。

SSO: std::string のコンテキストにおける頭字語 SSO の意味

于 2012-05-14T17:00:01.030 に答える
2

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.

于 2012-05-14T16:58:15.163 に答える
1

はい、コンパイラは必要なコードを生成して を作成し、std::stringそれを引数としてx関数に渡します。

于 2012-05-14T16:50:29.457 に答える
0

キーワードでマークされていない限り、単一の引数を取るコンストラクターはexplicit、引数の型からオブジェクトのインスタンスに暗黙的に変換するために使用されます。

この例でstd::stringは、引数を取るコンストラクターがあるconst char*ため、コンパイラーはこれを使用して、文字列リテラルをオブジェクトに暗黙的に変換しstd::stringます。次に、その新しく作成されたオブジェクトの const 参照が関数に渡されます。

詳細は次のとおりです: C++ での明示的なキーワードの意味は何ですか?

于 2012-05-14T16:54:21.793 に答える