- #include<iostream>
- using std::cout;
- using std::endl;
- template<typename T>
- void swap(T&a, T&b){
- a = a ^ b;
- b = a ^ b;
- a = a ^ b;
- }
- int main(){
- short s = 50;
- //error: invalid initialization of reference of type 'int&' from expression of type 'short int'
- //无效的初始化:用'short int'类型的表达式来初始化'int&'类型的引用。
- //原因:用左值来初始化引用时,类型必须一致,不允许隐式转换。
- //int &ri1 = s;
- //invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'
- //无效的初始化:用'int'类型的右值来初始化'int &'类型的non-const引用。
- //原因:用右值来初始化引用时,会产生一个同类型的匿名临时变量,对表达式的值进行隐式转换,再对这个临时变量赋值。
- //int &ri2 = 50;
- //如果允许对这个临时变量定义一个non-const类型的引用,那么后续代码对这个引用的写操作毫无意义。例如:
- //int &i = 3;
- //int& j = 4;
- //swap<int>(i,j);
- //将无法对i,j进行交换。
- //有效的初始化:用'int'类型的右值来初始化'int &'类型的const引用。
- const int &ri3 = 60;
- }
下面的代码显示,用右值初始化一个引用时,生成了一个匿名临时变量:
- #include<iostream>
- using std::cout;
- using std::endl;
- class TestType{
- int m_data;
- public:
- TestType() : m_data(0) {
- cout << __FUNCTION__ << "(), this = " << this;
- cout << ", m_data = (" << &m_data << ", " << m_data << ")\n";
- }
- //TestType(int val) : m_data(val) {
- // cout << __FUNCTION__ << "(int val), this = " << this;
- // cout << ", m_data = (" << &m_data << ", " << m_data << ")";
- // cout << ", val = (" << &val << ", " << val << ").\n";
- //}
- TestType(const int &rv) : m_data(rv) {
- cout << __FUNCTION__ << "(int &rv), this = " << this;
- cout << ", m_data = (" << &m_data << ", " << m_data << ")";
- cout << ", rv = (" << &rv << ", " << rv << ").\n";
- }
- };
- int main(){
- cout << "sizeof(TestType) = " << sizeof(TestType) << endl;
- TestType dat1;
- TestType dat2(100);
- int i = 200;
- cout << "i = (" << &i << ", " << i << ")\n";
- TestType dat3(i);
- return 0;
- }
运行结果:
sizeof(TestType) = 4
TestType(), this = 0x7fffc5b81cd0, m_data = (0x7fffc5b81cd0, 0)
TestType(int &rv), this = 0x7fffc5b81ce0, m_data = (0x7fffc5b81ce0, 100), rv = (0x7fffc5b81cfc, 100).
i = (0x7fffc5b81cfc, 200)
TestType(int &rv), this = 0x7fffc5b81cf0, m_data = (0x7fffc5b81cf0, 200), rv = (0x7fffc5b81cfc, 200).
来源: http://www.bubuko.com/infodetail-2116961.html