c++ - 常量左值引用
PHP中文网
PHP中文网 2017-04-17 13:49:58
0
3
374

为什么常量左值引用可以赋右值,右值不是没有内存地址吗?但是引用不是相当于一个别名吗?那么左值的变量的地址是哪里的呢?

#include <iostream>
#include <cstring>
#include <string>
#include <typeinfo>

using namespace std;

int main()
{
    int a = 2;
    int& b = a;
    cout << &a << endl;
    cout << &b << endl;
    const int& c = 2;
    cout << &c << endl;
    return 0;
}

像上面的这段代码,a与b的地址都是一样的,但是我不清楚c的地址是如何确定的。请问这该怎么解释?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(3)
大家讲道理

Constant lvalue references can extend the life cycle of a temporary object
The Rvalue references section in http://en.cppreference.com/w/cpp/language/reference talks about it
C++ The concept of temporary quantities is also included in primer’s chapter on citations

Peter_Zhu

int type occupies 4 bytes
so 3c - 38 = 4

Peter_Zhu

c is a const constant declared after a and b. The system re-allocates an address to it after the address of a (b)
An int occupies 4 bits, so 0x72fe38 + 4 = 0x72fe3c
In hexadecimal 38 + 4 = 3c

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template