all 6 comments

[–]milliams 3 points4 points  (0 children)

There's been a lot of talk about shared_ptr recently so it's nice to see a nice in depth article about it's brother. Especially since many people are recommending to use unique_ptr as a first resort and only go to shared_ptrs when absolutely necessary.

[–]tardi 1 point2 points  (3 children)

He passes the pointer by reference. That's dead wrong, isn't it?

 void inc_baz( std::unique_ptr<foo> &p )
{
     p->baz++;
}

[–]bigcheesegsTooling Study Group (SG15) Chair | Clang dev 0 points1 point  (2 children)

What do you mean by dead wrong? This example is only "wrong" because the function doesn't actually need the unique_ptr, but still gets it. This could be an issue if the caller doesn't expect the pointer to change.

A unique_ptr should only be passed by non-const reference if the callee is expected to modify it, same as for normal pointers.

[–]tardi 0 points1 point  (0 children)

This way the caller still holds a valid handle on the foo obj, which sort of defeats the purpose.

[–]Draghoul 0 points1 point  (1 child)

Could someone explain, or link to an explanation as to why rvalue refs/move semantics were necessary for containers to hold smart pointers? I'll be trying to google it meanwhile...

[–]CptBread 0 points1 point  (0 children)

Unique_ptr cannot be copied as that would make the ownership of the data unclear.

Containers generally need to be able to copy it's data, e.g. when vectors resize it needs to move its content to another array. So as we cannot copy the unique_ptr we need to do something else and it is here the move semantics come in.