引用初始化的重要细节

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#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;
}

下面的代码显示,用右值初始化一个引用时,生成了一个匿名临时变量:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#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).







      本文转自FrankNie0101 51CTO博客,原文链接:http://blog.51cto.com/frankniefaquan/1934509,如需转载请自行联系原作者



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值