DEV Community

Discussion on: Pointers and References: Design Goals and Use Cases

Collapse
 
pgradot profile image
Pierre Gradot • Edited

they are both allocated on the heap.

references can also allocate memory for a single entity on the heap.

References and pointers are not necessarily on the heap. And reference cannot allocate (strictly speaking). But references and pointers can reference/point to variables that are allocated on the heap, while being themselves on the stack.

Maybe that's what you meant ;)

References can be thought of as a constant pointer T const* c_ptr = &obj and should not be confused with const T* ref = &obj

The const should be after the * (just like in your code sample below).

Returning references over local variables may cause undefined behavior (dangling references)

Same thing with pointers.

My rule of thumb for pointers vs references: if you can use a reference, then use a reference. Otherwise, use a pointer.

Collapse
 
iamdeb25 profile image
Dave Amiana

Right. Thank you for clarifying what I meant. I appreciate it.