加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么rvalue / const引用有内存地址和大小?

发布时间:2020-12-16 10:36:35 所属栏目:百科 来源:网络整理
导读:我到处读到引用不是对象,它们只是别名,它们在内存中没有位置 int x = 256;int rx = x;std::cout x " " x std::endl; // Output: 256 0x15FAB0std::cout rx " " rx std::endl; // Output: 256 0x15FAB0// seems legit ... fair enough ... 现在考虑以下内容 c
我到处读到引用不是对象,它们只是别名,它们在内存中没有位置

int x = 256;
int& rx = x;

std::cout << x << " " << &x << std::endl;       // Output: 256  0x15FAB0
std::cout << rx << " " << &rx << std::endl;     // Output: 256  0x15FAB0

// seems legit ... fair enough ...

现在考虑以下内容

const int& r1 = 8;      // lvalue ref to const int
int&& r2 = 32;          // rvlaue ref to int
const int&& r3 = 128;   // rvalue ref to const int

std::cout << r1 << " " << &r1 << std::endl;     // Output: 8     0x15FA8C
std::cout << r2 << " " << &r2 << std::endl;     // Output: 32    0x15FA74
std::cout << r3 << " " << &r3 << std::endl;     // Output: 128   0x15FA5C

// and ...

std::cout << sizeof(r1) << std::endl;   // Ouput: 4
std::cout << sizeof(r2) << std::endl;   // Ouput: 4
std::cout << sizeof(r3) << std::endl;   // Ouput: 4

那么为什么这些引用表现得像对象一样,它们确实有值,内存地址和大小……它们是否与引用规则不同?
他们是在堆栈上还是在其他地方?

解决方法

我猜你真正的问题是“当他们没有引用任何名字时,rvalue / const引用在哪里?”

const int& r1 = 8;      // lvalue ref to const int
int&& r2 = 32;          // rvlaue ref to int
const int&& r3 = 128;   // rvalue ref to const int

在上述所有三种情况下,编译器在临时位置分配空间,将值放在那里,并为您提供对该值的引用.允许编译器这样做,因为它可以保证临时位置保持只读.

这就是你的引用获取它们的地址的方式 – 对象(8,32,128)仍然存在,因为编译器会为你创建它们.这些隐藏对象的地址成为引用的地址; sizeof运算符报告这些隐藏对象的大小.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读