Are references also allocated to memory space?

Asked 2 years ago, Updated 2 years ago, 24 views

It is often described as a new name given to reference targets when describing references to C++ I'm a little confused because there's a saying on the Internet that anonymous variables are assigned. Is a new variable allocated to memory space when declaring a reference?

c++

2022-09-22 19:49

1 Answers

http://en.cppreference.com/w/cpp/language/referenceSee the following:

References are not objects; they do not necessarily occupy storage, although the compiler may allocate storage if it is necessary to implement the desired semantics (e.g. a non-static data member of reference type usually increases the size of the class by the amount necessary to store a memory address).

Because the reference is not an object, it does not necessarily require storage space, but if the compiler is needed, it can occupy storage space depending on the implementation. That is, may or may not be allocated to memory space.

As mentioned above, the reference is not an object, so sizeof cannot measure the size. sizeof(int&) is calculated equal to the value of sizeof(int). Therefore, you can measure the size of the reference in the following ways:

#include <iostream>

struct IntRef {
    int& ref;
};
struct CharRef {
    char& ref;
};
int main() {
    std::cout << "sizeof int& : " << sizeof(IntRef) << std::endl;
    std::cout << "sizeof char& : " << sizeof(CharRef) << std::endl;
    std::cout << "sizeof void* : " << sizeof(void*) << std::endl;
    return 0;
}

The results of executing the above code are as follows. The size may vary from system to system, but you can see that void* and the references are the same size.

sizeof int& : 8
sizeof char& : 8
sizeof void* : 8

You can also check the assembly to find out the size. Below is the assembly code when the C++ code using references was compiled into GCC 7.3 (https://godbolt.org/g/peksus.

int main() {
    int value = 10;
    int& ref = value;
    int* ptr = &value;
    return 0;
}
main:
  push rbp
  mov rbp, rsp
  mov DWORD PTR [rbp-20], 10
  lea rax, [rbp-20]
  mov QWORD PTR [rbp-8], rax
  lea rax, [rbp-20]
  mov QWORD PTR [rbp-16], rax
  mov eax, 0
  pop rbp
  ret

where mov QWORD PTR [rbp-8], rx is the content of int&ref=value;, mov QWORD PTR [rbp-16], and rx are the contents of int* ptr=&value.

rbp You can see that only the following numbers are different. This means that the reference has the same actual behavior as the pointer and occupies its own memory space in the position rbp-8 rather than rbp-20.

In summary, the reference user does not necessarily need memory space by standard, but takes up memory space depending on the implementation of the compiler, which also depends on the implementation, but takes up memory space of typically the same size as a pointer.


2022-09-22 19:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.