Looking at references in C++ I noticed that all implementations I looked at used a pointer internally.
Does the C++ Standard guarantee that a reference will use a pointer internally or would it be ok for an implementation to use a more "efficient" solution? (I would currently not see how it could be done "better" because when a new stack frame is created there's not really a bulletproof way to know easily at what offset from the stack base pointer the variable that is being referenced is at because the stack is quite dynamic)
Note: I do understand the difference between a pointer and a reference in C++ (This question has nothing to do with that)
The pointer content is passed by reference but the pointer itself is still passed by value, i.e. reassinging it to some other pointer will not be reflected upon the exit from the method because the pointer will be set to point to the same memory block as before the call. Think of it as a simple int variable.
References are usually preferred over pointers whenever you don't need “reseating”. This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.
The correct answer is "option 1". The reference is used to refer to an existing variable in an alternative name. A pointer can have a NULL value but a reference cannot have. A reference doesn't need any explicitly dereferencing mechanism.
References are Safer and Easier to Use References don't have to be dereferenced like pointers and can be used like normal variables (as an alias for some other variable). It is necessary to pass objects as a reference in a copy constructor.
If you mean that a reference requires the compiler to allocate storage for a pointer, then that's unspecified.
§ 8.3.2/4
It is unspecified whether or not a reference requires storage.
EDIT: To record Martin Bonner's comment as a useful, practical note,
[F]or debugging purposes it can be quite useful to know what is going on "under the hood". (E.g. to answer questions like "why hasn't this gone completely off the rails?"). In practise, compilers all implement references as pointers (unless they can optimize the reference completely away).
No, it does not make any guarantees about how references are implemented. The C++ language only defines the semantics of references, not their implementation.
The standard doesn't say how a reference is implemented, just how it works.
It also doesn't say anything about stack frames, that's another implementation detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With