Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ RvalueとLvalue参照 | セクション
C++のポインタと参照

RvalueとLvalue参照

メニューを表示するにはスワイプしてください

lvaluervalue の概念は、式の分類に関連しています。

  • lvalue(左辺値):識別可能なメモリ位置を持つオブジェクトを参照する式。変更可能なオブジェクトを表します。

  • rvalue(右辺値):一時的または使い捨ての値を表す式。

一時値

一時値は、式の評価中に生成される短命な中間結果です。

rvalue.h

rvalue.h

12345678
// `(27 + 6 + 3 + 2)` is a tempopary value int sum = 27 + 6 + 3 + 2; // `static_cast<float>(sum)` is a tempopary value float avarage = static_cast<float>(sum) / count; // std::max(7, 9) will return a tempopary value int largest = std::max(7, 9);

一時的な値はコンパイラによって自動的に管理され、生成された式や操作の期間中のみ存在します。その後、通常は破棄され、結果はターゲット変数に格納されるか、必要に応じて使用されます。

ムーブセマンティクス

rvalue参照はダブルアンパサンド(&&)で表されます。

lvalue参照とrvalue参照の唯一の違いは、rvalue参照は一時オブジェクトにバインドできるのに対し、lvalue参照はできない点です。

int&& ref_value = 5 * 5;
Note
注意

この文脈でrvalue参照を使用してもあまり実用的ではありません。単純なリテラルに対してrvalue参照を使う利点はありません。

lvaluervalue 参照の組み合わせは、ムーブセマンティクス をサポートするために使用され、リソースを不要なコピーなしで あるオブジェクトから別のオブジェクトへ転送することを可能にします。以下の例を参照してください。

swap.h

swap.h

123456
std::string swap(std::string& a, std::string& b) { std::string tmp(a); // We have two copies of string `a` a = b; // Now we have two copies of string `b` b = tmp; // And now we have two copies of string `tmp` }

しかし、ab のコピーは必要ありません。単にそれらを入れ替えたかっただけです。もう一度試してみましょう。

main.cpp

main.cpp

1234567891011121314151617181920212223
#include <iostream> void swap(std::string &a, std::string &b) { // Move the content of a into temp std::string temp(std::move(a)); // Move the content of b into a a = std::move(b); // Move the content of temp into b b = std::move(temp); } int main() { std::string a = "Hello\n"; std::string b = "Bye\n"; swap(a, b); std::cout << a << b; }

std::move(): lvalue を rvalue 参照に変換し、ムーブセマンティクスおよび所有権の移譲をコピーせずに可能にする。

question mark

lvalue とは何か?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  10

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  10
some-alt