我正在学习通过参考传递,这是我所做的测试:
#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;
}
这是我得到的结果:
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
我的问题是:
如果我们传递一个常量表达式,它总是会触发非常量右值引用吗?在什么情况下它会触发常量右值引用(为什么 s6 不触发它?)
为什么非常量引用和常量右值引用是非法的?
我预计a不能改变s3,但是为什么内部范围内的b可以改变s3?如果将新对象 s3 分配给 b 正在分配新引用,为什么当我将 s4 分配给它并且 s3 被更改并且之后 s4 为空时?
抱歉问了太多问题......当所有问题都得到回答时,我会增加分数:) 参考只是把我的困惑从指针带到了一个全新的水平。
我不知道如何增加分数......所以将等待 2 天直到有资格获得赏金然后选择答案。