dimanche 4 octobre 2020

When should a shared_ptr be passed as a raw pointer?

I was reading about how shared pointers should be passed around. I came across this link which states

Guideline: Use a non-const shared_ptr& parameter only to modify the shared_ptr. Use a const shared_ptr& as a parameter only if you’re not sure whether or not you’ll take a copy and share ownership; otherwise use widget* instead (or if not nullable, a widget&).

I had a two questions regarding the above mentioned statement

Question 1:

It states

.. otherwise use widget* instead (or if not nullable, a widget&).

Does this mean if we have something like this

std::shared_ptr<foo> f = std::make_shared<foo>();

And we need to pass it to a different method. That method should have the signature like

void doSomething(foo* ptr); //assuming its nullable

so to use it will be

doSomething(f.get());

Is this correct ? If so then would this not be dangerous ? if the reference count of f goes to 0 then ptr would basically be invalid ? In which situation would I want to create a method that takes in a raw pointer ? Why would I want to pass a smart pointer around like that ?

Question 2 What does modify mean here ? How do I modify a shared pointer ?

Use a non-const shared_ptr& parameter only to modify the shared_ptr

Aucun commentaire:

Enregistrer un commentaire