简体   繁体   English

shared_ptr类中get()成员的用途是什么?

[英]What are the uses of get() member from the shared_ptr class?

My question is that what are the various ways in which get() member from the shared_ptr class can be used? 我的问题是,可以使用shared_ptr类中的get()成员的各种方法是什么? And why can't we use delete to delete it? 为什么我们不能使用删除删除它?

If you had a function taking a raw pointer 如果你有一个函数采用原始指针

void f(T *t); // non-owning pointer

And you had a smart pointer to a T object, you could pass it to that function by using get() 你有一个指向T对象的智能指针,你可以使用get()将它传递给该函数

std::shared_ptr<T> sp{new T};  // or unique_ptr
//f(sp); // no good, type mismatch
f(sp.get()); // passes the raw pointer instead

APIs taking raw pointers are common, and still useful. 采用原始指针的API很常见,但仍然很有用。 I'd suggest you watch this part of Herb Sutter's talk from CppCon 2014, and probably the parts around it. 我建议你看一下2014年CppCon 上Herb Sutter的演讲的这一部分 ,可能还有它周围的部分。

You should not attempt to delete this pointer, the smart pointer classes assume you will not do anything like that, and will still free the managed object in their own destructors when the time comes (after all, how would it know you deleted it?). 应该试图删除这个指针,智能指针类假设你不会做这样的事情,并会仍然可以自由在自己的析构函数被管理对象在时机成熟时(毕竟,如何将它知道你删除了?) 。

The smart pointer's job is to manage the object and delete it at the right time, if you want to manually manage the lifetime of the object (not usually recommended) then use a raw pointer. 智能指针的作用是管理对象并在正确的时间将其删除,如果您想手动管理对象的生命周期(通常不推荐),则使用原始指针。

If you do want to assume ownership of a unique_ptr you can do so by calling release() . 如果您确实想要拥有unique_ptr所有权,可以通过调用release()

Usually you would use get() when you need to pass a raw pointer to an API that accepts such a pointer. 通常,当需要将原始指针传递给接受此类指针的API时,您将使用get()

The shared_ptr class manages the ownership of the pointer, so it will automatically delete the owned memory when the lifetime of the smart pointer ends. shared_ptr类管理指针的所有权,因此当智能指针的生命周期结束时,它将自动删除拥有的内存。 If you try to delete the memory yourself then when the shared_ptr tries to deallocate you will wind up with undefined behavior. 如果您尝试自己删除内存,那么当shared_ptr尝试解除分配时,您将会遇到未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM