C++ std::unique_ptr::get 有什么意义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10802046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
what's the point of std::unique_ptr::get
提问by lezebulon
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?
首先不会std::unique_ptr::get
破坏拥有 unique_ptr 的目的吗?我本来希望这个函数改变它的状态,所以它不再持有指针。std::unique_ptr::get 有实际有用的用途吗?
回答by Nikolai Fetissov
You use it every time you need to pass raw pointer to, say, a C function:
每次需要将原始指针传递给 C 函数时都会使用它:
std::unique_ptr<char[]> buffer( new char[1024] );
// ... fill the buffer
int rc = ::write( fd, buffer.get(), len );
回答by bames53
std::unique_ptr
provides unique ownership semantics safely. However that doesn't rule out the need for non-owningpointers. std::shared_ptr
has a non-owning counterpart, std::weak_ptr
. Raw pointers operate as std::unique_ptr
's non-owning counterpart.
std::unique_ptr
安全地提供独特的所有权语义。然而,这并不排除对非拥有指针的需要。std::shared_ptr
有一个非拥有的对应物,std::weak_ptr
。原始指针作为std::unique_ptr
的非拥有对应物运行。
回答by Nevin
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.
我倾向于遵循的规则是:如果被调用者没有搞砸生命周期/所有权,则不要向它传递智能指针;相反,传入原始 C++ 引用(首选)或原始指针。我发现将所有权问题与使用问题分开会更清晰、更灵活。
回答by R. Martinho Fernandes
When your hands are tied and you do need to pass a pointer to something, p.get()
reads better than &*p
.
当你的手被绑住并且你确实需要传递一个指向某物的指针时,p.get()
读起来比&*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.
有一个函数可以更改状态,因此unique_ptr
不再持有指针,而该函数名为release
。这对于将所有权转移到其他不提供直接构造的智能指针非常有用unique_ptr
。任何其他用途都有泄露资源的风险。
回答by Mikael
Herb Sutter has a good explanation (around 3:40) https://www.youtube.com/watch?v=JfmTagWcqoE
Herb Sutter 有一个很好的解释(大约 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.
主要优点是唯一指针会跟踪该指针还有多少其他引用。当您使用所有权时,您只能使用唯一指针。当你想用那个指针对数据做一些事情时,你传递原始指针。
回答by K-ballo
There is the obvious situation when you need to call a C API, or a poorly designed C++ API.
当您需要调用 C API 或设计不佳的 C++ API 时,情况很明显。