I’m confused about how c++ works.
From what I understand, the C++ language has this equivalence:
variable (name) <=> data in memory. (ex: int a = 5; // a <=> the value of this variable name stored in memory, here 5). In fact, even assembly doesn’t have this equivalence, the label corresponds to the
address of the data.
Incidentally, I’m having trouble (not pejoratively, as I’m sure there’s a reason) convincing myself of the need for this equivalence in C++. (It says in effective C++ to pass each object by const ref and then see what part of the object’s value we need to copy, perhaps all of it).
That said, this reasoning justifies the need for pointers (and references which are, as I understand it, *constant pointers with better semantics).
*not completely in the C++ sense, as they are potentially stored only in one of the registers and therefore have no address on the stack -> not real objects. (After observing compiled C++ code, this is even the case for pointers in situations where the compiler has no “red flag”, such as, for example, an expression with &ptr, which tells it that the ptr must indeed have an address in memory).Another way of understanding references, which I find works quite well, is to think that it’s another name for the object and that the type is different simply because of the initialization, which is different, and unauthorized operations, such as re-assignment. In my opinion, however, this reasoning is flawed, as it prevents us from understanding why passing by reference is also sometimes more economical than passing by value.
Anyway, after redefining my first operator, I realized that this line of reasoning made sense (for primitive types and for objects): In fact, the operator takes object addresses as arguments, which is necessary to access their values. We therefore deduce that 2 r-values are created and (usually) stored in registers: the 2 addresses (having the reference type in C++). Then, the operator “function” uses the 2 addresses to assign the value (<=> variable name in C++) of one to the other.
But then I come to a problem in my understanding of C++ that I can’t solve: *ptr has the type of the object (e.g. int and not int&), yet it’s a reference to the object (its address in memory).
I’m completely lost, I think!
Could someone save me in my understanding of pointers and references and how to interpret them at low level by giving me an “authoritative” explanation that is valid in all cases?
Ulysse Forest is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
5