0

How does alias internally work in C++?
Does it allocate its own memory like pointers?
Otherwise how does the compiler treat it?
Is it like C++ Macro preprocessor computing?

int x=5;
int &y=x; //Assembly of this???
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
alexHX12
  • 403
  • 2
  • 9
  • 2
    That is a C++ only feature, C does not have reference types – UnholySheep Oct 06 '21 at 19:11
  • These are called references. And they don't exist in C. – Barmar Oct 06 '21 at 19:11
  • Thanks, I've corrected it – alexHX12 Oct 06 '21 at 19:12
  • 1
    How it works is implementation-dependent. Also, reference variables are probably implemented differently from reference parameters to functions, since the latter change from one call to the next. – Barmar Oct 06 '21 at 19:13
  • 1
    The best way for you to understand it is to see it with your own eyes. In many debuggers (including visual studio), when you hit a breakpoint, you can turn on the "view assembly" view where you can see the assembly code. – kalyanswaroop Oct 06 '21 at 19:14
  • 1
    You can also use godbolt.org to see the assembly. – Barmar Oct 06 '21 at 19:14
  • 1
    A local reference is probably like a macro, the compiler just translates it automatically. A reference parameter is probably implemented as a hidden pointer. – Barmar Oct 06 '21 at 19:15
  • 1
    The compiler can choose from many ways to implement it. In your example, there is [probably **no assembly** generated](https://godbolt.org/z/en91xb7Ex). `y` is simply another way to type `x`. – Drew Dormann Oct 06 '21 at 19:18

1 Answers1

4

Those are called references.

The standard doesn't describe how they (or anything else) work on the assembly level.

In practice, they are implemented as pointers, unless the compiler optimizes them away (which is easier for references compared to pointers, because they can't be reassigned).

They are unrelated to macros, the preprocessor doesn't know about references.

The standard contains some interesting wording for references: they "are not objects", the consequence being that you can't legally meaningfully examine their memory layout and modify it. But this is mostly a peculiarity of the wording; for most purposes they work like immutable pointers.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207