#How do pointers and reference work with ownership?

27 messages · Page 1 of 1 (latest)

bleak vessel
#

I've been trying to understand ownership and from what I've gathered it's just a responsibility for managing lifetime. but I am a little confused when working with raw/smart pointers and references.

For example if I return something as some form of pointer the ownership now belongs to the caller? (I assume there's an exception to shared_ptr since it's shared) Meanwhile a reference would just imply that the caller is using it, but doesn't actually own it and therefore doesn't need to worry about managing its lifetime?

gentle socketBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

golden swallow
#

smart pointers represent ownership

#

raw pointers/references represent just a way to refer to an object somewhere else

#

smart pointers reside with whoever is responsible for managing the lifetime of the object

#

everyone who's just supposed to use the object but not have any part in determining its lifetime just gets a raw pointer/reference

#

different kinds of smart pointers just represent different kinds of ownership models. but smart pointers are always about managing the lifetime in some way.

#

passing a smart pointer means passing ownership/control over the object's lifetime

#

passing a raw pointer/reference just means "here's the thing i want you to use"

bleak vessel
#

So using raw pointers doesn't dictate imply ownership(?) not sure if that's the right word lol

#

thought it would be similar because whoever uses the pointer would have to like call delete when they're done? but ok interesting, thanks

dusk oracle
#

Only use delete when you use new

#

Smart pointers delete themselves when they go out of scope

gentle socketBOT
#

@bleak vessel Has your question been resolved? If so, type !solved :)

golden swallow
#

but manually managing lifetime with raw pointers is incredibly error prone.

#

that's why we have smart pointers.

#

but sure, this is ultimately (mostly) all just a matter of convention.

bleak vessel
#

yeah I just looked it up and found out there's a thing called "non-owning pointer" which I assume is what you mean by this" raw pointers/references represent just a way to refer to an object somewhere else"?

golden swallow
#

yes

#

raw pointers/references, i.e., T*/T&, are non-owning

bleak vessel
#

out of curiosity now would a weak_ptr be equivalent to a non-owning pointer?

#

!solved

gentle socketBOT
#

Thank you and let us know if you have any more questions!

This thread is now set to auto-hide after an hour of inactivity

golden swallow
granite parcel
#

Raw pointers should not represent ownership. The language does not prevent this, but it's much better to use managed pointers.