search

Home  >  Q&A  >  body text

c++ - 常量左值引用

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

#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中文网2774 days ago376

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 13:51:58

    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

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 13:51:58

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

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 13:51:58

    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

    reply
    0
  • Cancelreply