Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smart pointers vs Reference

I bet this has probably been asked before, but since reference (int& name) is taken the same as reference counting by searchers, couldn't find a single thing.

Why isn't there ever mention of references as alternates to smart pointers? Is it just for the null case, or is there something else? What advantages/disadvantages are there to using either?

like image 301
efaj Avatar asked Aug 25 '12 06:08

efaj


1 Answers

I think you have your terminology mixed up. A reference and the term reference counting aren't really talking about the same thing.

References and smart pointers, or even pointers for that matter are very different and not interchangeable.

A reference cannot be reseated. Meaning that once you have a reference, it can only refer to the thing it initially referred to. A reference is merely a memory address.

A pointer on the other hand, points to a memory address; it can be changed to point to different memory addresses.

When someone says a smart pointer does reference counting, they mean the smart pointer is keeping count of how many objects are referring to the memory the smart pointer is pointing at. This is different from a reference.

I hope that helps.

like image 147
anio Avatar answered Sep 21 '22 21:09

anio