开发者

C++: Any great difference in _implementation_ of the reference and the pointer

开发者 https://www.devze.com 2023-04-12 23:40 出处:网络
I caught that I use references not understanding开发者_Python百科 how they really work (that\'s why I use them not so often).

I caught that I use references not understanding开发者_Python百科 how they really work (that's why I use them not so often).

Pointer seem to be implemented simply somehow like: a simple WORD variable with address of some other variable. We copy it when we pass it as a parameter to function.

And what happens when we pass reference as a parameter? The same old way?


The two don't have as much in common as you'd think, really.

A reference exists at a higher level of abstraction in the compiler. It doesn't need to generate any code at all. It is essentially an alias for an object, so whenever it is used, the compiler treats it as a use of the referenced object. Of course, sometimes, the compiler will choose to represent code which uses a reference by generating a pointer value which can be passed around as needed, but a reference is really not tied to a specific representation.

A pointer is much more close to the metal. It is a variable which stores an address.


On the particulars of how they are implemented, it depends on the context in which they are used. If the reference is valid only within a scope, the compiler can remove the reference (alias) and use the referred object whenever needed.

If the reference cannot be proven not to escape the current scope (as in a member of a class that could be dynamically allocated), most compilers implement it with a pointer that is automatically dereferenced on use (and providing the rest of the guarantees that are available for references and not for plain pointers).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号