I was learning passing by reference, and here is the test I did:
#include <iostream>
using namespace std;
int i = 0;
//If this is uncommented, compiler gives ambiguous definition error.
//void paramCheck (string s) {
// cout << ++i << ". Param is var.\n";
//}
void paramCheck (const string& s) {
cout << ++i << ". Param is const ref.\n";
}
void paramCheck (string& s) {
cout << ++i << ". Param is non-const ref.\n";
}
void paramCheck (const string&& s) {
cout << ++i << ". Param is const rvalue-reference.\n";
}
void paramCheck (string&& s) {
cout << ++i << ". Param is non-const rvalue-reference.\n";
}
int main(int argc, char **argv) {
//Function call test
paramCheck("");
paramCheck(string{""});
string s3{""};
paramCheck(s3);
const string s4{""};
paramCheck(s4);
//Illegal
//string& s{""};
//paramCheck(s);
const string& s5{s3};
paramCheck(s5);
string&& s6{""};
paramCheck(s6);
//Illegal
//const string&& s{s1};
//onstFP(s);
//Reference test
string a = s3;
a = "a changed s3";
cout << s3;
{
string& b = s3;
b = "b changed after assigning s3\n";
cout << "s3 is now " <<s3;
b = s4;
b = "b changed after assigning s4\n";
cout << "s3 is now " <<s3;
cout << "s4 is now " <<s4;
}
cin.get();
return 0;
}
And here is the result I get:
1. Param is non-const rvalue-reference.
2. Param is non-const rvalue-reference.
3. Param is non-const ref.
4. Param is const ref.
5. Param is const ref.
6. Param is non-const ref.
s3 is now b changed after assigning s3
s3 is now b changed after assigning s4
s4 is now
My question is:
If we pass a constant expression, it always triggers non-constant rvalue-reference? Under what condition it will trigger constant rvalue-reference (and why s6 is not trigging it?)
Why non-constant reference and constant rvalue-reference are illegal?
I expected a cannot change s3, but why b in the inner scope can change s3? If assigning a new object s3 to b is assigning a new reference, why when I assign s4 to it and s3 got changed and s4 is empty afterwards?
Sorry for asking too many questions... I will increase the points when all questions are answered :) The reference just brings my confusion from pointer to a whole new level.
I don't know how to increase the point... so will wait for 2 days till eligible for bounty then choose the answer.
&&
syntax is either referring to a rvalue-reference or a universal-reference (in templates). – dyp Jul 31 '13 at 20:43