把引用放在结构里,其指针的本质就显现了

代码

#include <cstdio>

using namespace std;

struct st {
    int &ele;

    st(int &ele) : ele(ele) {}
};

struct st1 {
    int &ele;
};
struct st2 {
    int ele;
};
struct st3 {
    int ele01;
    long long ele02;
};
struct st4 {
    st3 &ele;
};
struct st5 {
    st3 &ele01;
    st3 &ele02;
};

void printRefSize(int &ref) {
    int &rref = ref;
    printf("size of int ref is %llu\n", sizeof(ref));
    printf("size of int rref is %llu\n", sizeof(rref));
}

void refSizeTest() {

    int a = 1;
    int &b = a;
    st s(a);
    st2 s2;
    st2 &stf2 = s2;

    /* 裸的引用,大小等于引用的类型的大小 */
    printf("size of pure ref\n");
    printf("size of int is %llu\n", sizeof(a));
    printf("size of int ref is %llu\n", sizeof(b));
    printf("size of stf2 ref is %llu\n", sizeof(stf2));
    printRefSize(a);
    printRefSize(b);
    printf("\n");

    /* 引用放在结构里面,编程了指针的大小 */
    printf("size of pure ref in struct\n");
    printf("size of int st is %llu\n", sizeof(s));
    printf("address of a: %p\n", &a);
    printf("address of b: %p\n", &b);
    printf("address of s: %p\n", &s);
    /* 结构中引用的地址还是初始类型元素的地址,和a、b是相同的 */
    printf("address of s-ele: %p\n", &s.ele);
    /* 此时s中只有引用,可以看看s里面到低是啥 */
    printf("content of s: %llX\n", s);
    printf("true address of s and s-ele: %p\n", &s);
    printf("\n");

    /* 不同的struct内容,引用的大小总是指针的大小 */
    printf("size of different ref in struct\n");
    printf("size of int st1 is %llu\n", sizeof(st1));
    printf("size of int st2 is %llu\n", sizeof(st2));
    printf("size of int st3 is %llu\n", sizeof(st3));
    printf("size of int st4 is %llu\n", sizeof(st4));
    printf("size of int st5 is %llu\n", sizeof(st5));
    /* 如果把s的内容当成指针,其指向的 */

}

int main() {
    refSizeTest();
    return 0;
}

运行结果

size of pure ref
size of int is 4
size of int ref is 4
size of stf2 ref is 4
size of int ref is 4
size of int rref is 4
size of int ref is 4
size of int rref is 4

size of pure ref in struct
size of int st is 8
address of a: 0000009BA1EFF860
address of b: 0000009BA1EFF860
address of s: 0000009BA1EFF868
address of s-ele: 0000009BA1EFF860
content of s: 9BA1EFF860
true address of s and s-ele: 0000009BA1EFF868

size of different ref in struct
size of int st1 is 8
size of int st2 is 4
size of int st3 is 16
size of int st4 is 8
size of int st5 is 16

说明

从第61行看到,结构s的成员只有int引用,s的内容就是int引用ele的内容,其内容就是引用原值的地址,s.ele是一个地址,s.ele是一个指针;

参考

下面这篇CSDN从汇编层面看引用,和指针是非常相似的,并且其通过指针工具修改了引用的实际内容;
C++ 引用是否占用内存空间?

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值