2015-01-03 8 views
5

多くの人は、constの値の参照がC++ 11言語の一部であることを知らない人がいます。 Thisブログ記事ではそれらについて説明していますが、バインディングルールについて間違っているようです。const &&のC++ 11バインディングルール

struct s {}; 

void f (  s&); // #1 
void f (const s&); // #2 
void f (  s&&); // #3 
void f (const s&&); // #4 

const s g(); 
s x; 
const s cx; 

f (s()); // rvalue  #3, #4, #2 
f (g()); // const rvalue #4, #2 
f (x); // lvalue  #1, #2 
f (cx); // const lvalue #2 

注非対称性::のconst左辺値参照は右辺値にバインドすることができますが、 のconst右辺値参照は左辺値にバインドできないブログを引用。 では、これによりconst左辺値参照がすべてのことを行うことができるようになります。右辺値参照は、複数の値を持つことができます(つまり、左辺値にバインドします)。

サンプルコードに関するコメントは、GCC 4.9(-std = C++ 14フラグセット)のインストール時にチェックアウトされているようです。したがって、ブログの文章とは異なり、const &&const &に、const &&には、const &は、const &にのみバインドする必要があります。実際のルールは何ですか?この文脈で「結合」http://coliru.stacked-crooked.com/a/794bbb911d00596e

+0

'のconst &&'(&&すなわち 'のconst'と '&&')のみ**右辺値にバインドできます**。ブログはテキストの通りです。 – bolov

+0

@bolov、デモをご覧ください。何か不足していますか? – ThomasMcLeod

+0

はい、それは 'const && 'への' const& 'バインディングです – bolov

答えて

3

は、特定のオブジェクトへの参照を結ぶ意味:ここで


const &&はGCC 4.9で const&への結合を示すように見えるのデモです。

int a; 

int &b = a; // the reference is 'bound' to the object 'a' 

void foo(int &c); 

foo(a); // the reference parameter is bound to the object 'a' 
     // for this particular execution of foo. 

http://coliru.stacked-crooked.com/a/5e081b59b5e76e03

それでは引用読み:

注非対称性を:のconst左辺値参照は右辺値にバインドすることができますが、

void foo(int const &); 

foo(1); // the const lvalue reference parameter is bound to 
     // the rvalue resulting from the expression '1' 

http://coliru.stacked-crooked.com/a/12722f2b38c74c75

const rvalue参照は左辺値にバインドできません。特に

void foo(int const &&); 

int a; 

foo(a); // error, the expression 'a' is an lvalue; rvalue 
     //references cannot bind to lvalues 

http://coliru.stacked-crooked.com/a/ccadc5307135c8e8

、これは(即ち、左辺値に結合する)のconst右辺値参照をよりことができるが、すべてを行うことができるのconst左辺値の参照を行います。

void foo(int const &); 

foo(1); // const lvalue reference can bind to rvalue 

int a; 
foo(a); // and lvalue 

http://coliru.stacked-crooked.com/a/d5553c99e182c89b

+0

これは観測できませんが、 '1'を' int const& 'にバインドすると、' 1'で初期化された一時オブジェクトが作成され、一時オブジェクトが参照にバインドされます。基本型のprvalue式は* values *ですが、アドレスはありません。 – dyp

+0

@dyp rvalue参照に '1'をバインドするときに同様の一時オブジェクトが得られます:' 1'で初期化されたrvalueパラメータのアドレスを取ることができます(rvalue参照変数はlvalue式を混乱させるほど十分に...) /coliru.stacked-crooked.com/a/d2c67961cf15072c – bames53

関連する問題