1

From what I understand, pointers hold the addresses of a value, and references can be thought as const pointers.

From this sample code:

int main() {
    int i = 1;
    int &ri = i;
    int *pi = &i;
    return 0;
}

The disassembly, both pointer and reference look exactly the same:

main:
    push    ebp
    mov ebp, esp
    sub esp, 16
    mov DWORD PTR [ebp-12], 1
    lea eax, [ebp-12]
    mov DWORD PTR [ebp-8], eax
    lea eax, [ebp-12]
    mov DWORD PTR [ebp-4], eax
    mov eax, 0
    leave
    ret

Are pointers and references only enforced by the compiler?

drum
  • 5,416
  • 7
  • 57
  • 91
  • 2
    struggling to understand what you mean by "enforced" . They are language features and they are working as intended – M.M Feb 23 '17 at 05:01
  • 1
    BTW inspecting unoptimized assembly is a poor way to learn , as you only really learn about one particular implementation's implementation details. You might overlook the fact that `int ri = 1; int &i = ri;` would have the same behaviour. – M.M Feb 23 '17 at 05:02

1 Answers1

4

From what I understand, pointers hold the addresses of a value, and references can be thought as const pointers.

That's a simplistic view. The standard defines their behavior. It's up to an implementation to figure out how to support that behavior.

Given

int i = 0;
int& ref = i;
int* ptr = &i;

the standard mandates that

&ref == &i

and

&ptr != &i;

Hence, it may make sense to think of references as const pointers for some aspects of its behavior but it definitely does not make sense for all aspects of its behavior.

R Sahu
  • 204,454
  • 14
  • 159
  • 270