0

R.33 is confusing me. Can someone care to explain further? The meaning of "reseating" doesn't seem to work here. ??

R.33: Take a unique_ptr& parameter to express that a function reseats thewidget Reason Using unique_ptr in this way both documents and enforces the function call’s reseating semantics.

Note “reseat” means “making a pointer or a smart pointer refer to a different object.”

Example void reseat(unique_ptr&); // "will" or "might" reseat pointer Example, bad void thinko(const unique_ptr&); // usually not what you want

1 Answers1

0

From the CPP guideline:

"reseat" means "making a reference or a smart pointer refer to a different object."


From modernescpp.com:

Let's look at each function signature in isolation. What does this mean from the function perspective?

void share(std::shared_ptr<Widget> shaWid)

I'm for the lifetime of the function body a shared owner of the Widget. At the begin of the function body, I will increase the reference counter; at the end of the function, I will decrease the reference counter; therefore, the Widget will stay alive, as long as I use it.


void reseat(std::shared_ptr<Widget>& shaWid)

I'm not a shared owner of the Widget, because I will not change the reference counter. I have not guaranteed that the Widget will stay alive during the execution of my function, but I can reseat the resource. A non-const lvalue reference is more like: I borrow the resource and can reseat it.


void mayShare(const std::shared_ptr<Widget>& shaWid)

I only borrow the resource. Either can I extend the lifetime of the resource nor can I reseat the resource. To be honest, you should use a pointer (Widget*) or a reference (Widget&) as a parameter instead, because there is no added value in using a std::shared_ptr.

Brandon
  • 386
  • 1
  • 4
  • 13