2016-10-06 5 views
0

パラメータをコピーせずに関数に渡すことは可能ですか?パラメータが '通過'されるために右辺値参照を使用できますか?

のは、例を作ってみましょう:

std::string check(std::string in, int &maxLen) 
{ 
    maxLen = std::max(maxLen, in.length()); 
    return in; 
} 

//main: 
    int maxCnt = 0; 
    std::cout 
     << check("test, ", maxCnt) 
     << check("two tests, ", maxCnt) 
     << check("three tests, ", maxCnt) 
     << maxCnt; 
// would output: "test, two tests, three tests, 13" 

私のC++コンパイラfooが、これはすでに離れて最適化することができるならば言って十分ではありません。

check(...)のシグニチャは、一時的な引数がとなるように見えるようにする必要があります。はコピーされません。

私の最初の推測されました:

std::string && check(std::string &&in, int &maxLen) 

これが正しければ、実装は次のように何に見えるのでしょうか?

備考:あなたが入力のいずれかのコピーを回避したい場合

  • std::stringはプレースホルダで、それがどの複合型
  • で動作するはず重複質問
+2

を渡す:最後の呼び出しでのオーバーロードの解決が選んだだろう

int max(0); std::string toto("Toto"); std::string lvalue = check(toto, max); // copy std::string const& const_ref = check(toto, max); // no-copy std::cout << check(toto, max) << std::endl; // no-copy 

:上check()定義して、まとめると

( 'const')参照... – rubenvb

+0

@rubenvb' 'std :: string check(std :: string const&in、int&maxlen)'は、入力が左辺値であるか一時的であるかにかかわらずコピーしませんか? –

+1

( 'const')参照も返す必要があります。そうでなければ、戻り値を構築する必要があります。 – rubenvb

答えて

0

に私をヒントしてください文字列として、あなたの関数を書く必要があります:

std::string const& check(std::string const& input, int& maxLen) { 
    maxLen = std::max(maxLen, input.size()); 
    return in; 
} 

Th e引数がconstで渡されたことはかなり明白です。なぜ帰ってくる? RVOではコピーを削除できないためです。 RVOは、関数内にオブジェクト(左辺値)を作成し、それを返すとき(左辺値も含む)に発生します。コンパイラは、オブジェクトが自動的にビルドされる場所にビルドすることによってコピーをエリートします。ここで、左辺値(std::string constまたはstd::stringのいずれか)を返すと、コンパイラは戻り値をどこかに保存し、その参照先から参照先へのコピーを実行する必要があることを確認します。 std::string const&を使用すると、operator <<std::basic_ostream)からのconst参照も処理されるため、これを回避できます。あなたがオブジェクトをコピーしたくない場合は、

template <class CharT, class Traits, class Allocator> 
std::basic_ostream<CharT, Traits>& 
    operator<<(std::basic_ostream<CharT, Traits>& os, 
       const std::basic_string<CharT, Traits, Allocator>& str); 
//    ^^^^^ const ref here for the string argument 
+0

'std :: string const&const_ref = check(" Toto "、max); // no-copy'も同様です。これは質問 –

+0

のユースケースであるため、 'std :: basic_ostream :: operator <<'を呼び出すと、オーバーロードの解決は[正しい呼び出し](http:// en。 cppreference.com/w/cpp/string/basic_string/operator_ltltgtgt) – Rerito

関連する問題