次のC++標準で登場しようとしているR値参照とは何ですか?
4 に答える
3
これにより、r値またはl値への参照を渡すことを呼び出したコードを区別できます。例えば:
void foo(int &x);
foo(1); // we are calling here with the r-value 1. This would be a compilation error
int x=1;
foo(x); // we are calling here with the l-value x. This is ok
r値参照を使用することにより、上記の最初の例のように一時的な参照を渡すことができます。
void foo(int &&x); // x is an r-value reference
foo(1); // will call the r-value version
int x=1;
foo(x); // will call the l-value version
これは、オブジェクトを作成する関数の戻り値を、そのオブジェクトを使用する別の関数に渡したい場合に、さらに興味深いものになります。
std::vector create_vector(); // creates and returns a new vector
void consume_vector(std::vector &&vec); // consumes the vector
consume_vector(create_vector()); // only the "move constructor" needs to be invoked, if one is defined
移動コンストラクターはコピーコンストラクターのように機能しますが、l値(const)参照ではなくr値参照を取得するように定義されています。r値セマンティクスを使用して、で作成された一時データからデータを移動し、ベクトル内のすべてのデータの高価なコピーを実行せずcreate_vector
に、それらを引数にプッシュすることができます。consume_vector
于 2009-05-11T05:40:53.387 に答える
3
C ++ 0x右辺値参照がデフォルトではないのはなぜですか?、それはそれらの実際の使用法をかなりよく説明しています。
于 2009-05-11T05:43:45.863 に答える
1
これはStephanT.Lavavejからの本当に長い記事です
于 2009-05-11T08:19:33.863 に答える
0
于 2009-05-11T05:33:41.263 に答える