vendredi 18 août 2017

Passing const reference or shared pointer / vector and assign to non-reference member

CPP check is complaining about this construction:

void setThing(std::shared_ptr<Thing> theThing) { memberThing = theThing; }

where memberThing is a std::shared_ptr<Thing>.

When changing to: void setThing(const std::shared_ptr<Thing>& theThing);

cppcheck is not complaining anymore.

I need a shared pointer, I can't guarantee theThing will exist forever, so I don't want to have a member reference. But why is a const reference working when assigning it to a not-reference member? And what happens actually? Is the shared pointer copied to memberThing? Where did the reference go?

And actually exactly the same question for

void setThings(std::vector<std::shared_ptr<Thing>> theThings) { memberThings = theThings; }

where memberThing is a std::vector<std::shared_ptr<Thing>>.

When using this construction, what is happening with the vector? Is it copied? What happens when the original vector is destroyed? Can I better use the first version or the second?

I am quite confused a const vector& can be assigned to a vector (not-reference). Is that a good idea anyway? What is the best thing to do in this situation? And why?

Aucun commentaire:

Enregistrer un commentaire