what's the point of std::unique_ptr::get

C++C++11PointersUnique Ptr

C++ Problem Overview


Doesn't std::unique_ptr::get defeat the purpose of having a unique_ptr in the first place? I would have expected this function to change its state so it holds no more pointer. Is there an actual useful use of std::unique_ptr::get?

C++ Solutions


Solution 1 - C++

std::unique_ptr provides unique ownership semantics safely. However that doesn't rule out the need for non-owning pointers. std::shared_ptr has a non-owning counterpart, std::weak_ptr. Raw pointers operate as std::unique_ptr's non-owning counterpart.

Solution 2 - C++

You use it every time you need to pass raw pointer to, say, a C function:

std::unique_ptr<char[]> buffer( new char[1024] );
// ... fill the buffer
int rc = ::write( fd, buffer.get(), len );

Solution 3 - C++

The rule I tend to follow is this: if the callee isn't mucking with lifetime/ownership, do not pass it a smart pointer; rather, pass in a raw C++ reference (preferred) or raw pointer. I find it far cleaner and more flexible to separate the concern of ownership from usage.

Solution 4 - C++

When your hands are tied and you do need to pass a pointer to something, p.get() reads better than &*p.

There is a function that changes the state so the unique_ptr doesn't hold a pointer anymore, and that one is named release. This is mostly useful to transfer ownership to other smart pointers that don't provide direct construction from a unique_ptr. Any other use risks leaking the resource.

Solution 5 - C++

There is the obvious situation when you need to call a C API, or a poorly designed C++ API.

Solution 6 - C++

Herb Sutter has a good explanation (around 3:40) https://www.youtube.com/watch?v=JfmTagWcqoE

The main advantage is that the unique pointer keeps track of how many other references there are to that pointer. You only work with the unique pointer when you are working with ownership. When you want to do something with the data with that pointer, you pass the raw pointer.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlezebulonView Question on Stackoverflow
Solution 1 - C++bames53View Answer on Stackoverflow
Solution 2 - C++Nikolai FetissovView Answer on Stackoverflow
Solution 3 - C++NevinView Answer on Stackoverflow
Solution 4 - C++R. Martinho FernandesView Answer on Stackoverflow
Solution 5 - C++K-balloView Answer on Stackoverflow
Solution 6 - C++MikaelView Answer on Stackoverflow