【发布时间】:2013-08-01 13:55:15
【问题描述】:
我正在学习通过引用传递,这是我所做的测试:
#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 天,直到有资格获得赏金然后选择答案。
【问题讨论】:
-
C++ 中没有引用的引用。
&&语法指的是右值引用或通用引用(在模板中)。 -
引用引用是指右值引用。该标准特别指出不允许引用引用。仅供参考。 C++11 § 8.3.2, p5: “不得有对引用的引用,不得有引用数组,也不得有指向引用的指针。...” 缩写为.. 好.. 简洁.
-
@DyP 是的,尽管通用引用实际上并不存在。 ;)
-
"它总是触发常量右值引用" 不,它没有,你的代码从不触发了常量右值引用。它总是触发非常量右值引用。
-
非常量引用不是非法的。 const r-value 听起来有点奇怪
标签: c++ c++11 parameter-passing rvalue-reference