我正在学习关于通过引用传递参数的知识,以下是我的测试结果:
#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没有触发它)?
为什么非常量引用和常量右值引用是不合法的?
我期望得到一个“不能改变s3”的结果,但为什么内部作用域中的b可以改变s3?如果将新对象s3分配给b是分配新引用,那么为什么当我将s4分配给它时,s3被更改并且s4后来为空?
抱歉问了这么多问题…当所有问题都得到回答时,我会增加奖励点数 :) 引用让我从指针的困惑进一步升级。
我不知道如何增加奖励点数…因此将等待2天直到有资格进行悬赏,然后选择答案。
&&
语法要么是指向右值引用,要么是通用引用(在模板中)。 - dyp