C++ 如何获取共享指针指向的对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6491955/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:15:05  来源:igfitidea点击:

How to get the Object being pointed by a shared pointer?

c++shared-ptrsharedsmart-pointers

提问by Pavan Dittakavi

I have a query. Can we get the object that a shared pointer points to directly? Or should we get the underlying RAW pointer through get()call and then access the corresponding object?

我有一个疑问。可以直接获取共享指针指向的对象吗?还是应该通过get()调用获取底层的RAW指针,然后访问对应的对象?

回答by Ken Wayne VanderLinde

You have two options to retrieve a reference to the object pointed to by a shared_ptr. Suppose you have a shared_ptrvariable named ptr. You can get the reference either by using *ptror *ptr.get(). These two should be equivalent, but the first would be preferred.

您有两个选项可以检索对 a 指向的对象的引用shared_ptr。假设您有一个shared_ptr名为的变量ptr。您可以使用*ptr或获取参考*ptr.get()。这两个应该是等价的,但首选第一个。

The reason for this is that you're really attempting to mimic the dereference operation of a raw pointer. The expression *ptrreads "Get me the data pointed to by ptr", whereas the expression *ptr.get()"Get me the data pointed to by the raw pointer which is wrapped inside ptr". Clearly, the first describes your intention much more clearly.

这样做的原因是您实际上是在尝试模拟原始指针的取消引用操作。表达式*ptr读取“获取我指向的数据ptr”,而表达式*ptr.get()“获取我包含在其中的原始指针指向的数据ptr”。显然,第一个更清楚地描述了您的意图。

Another reason is that shared_ptr::get()is intended to be used in a scenario where you actually needaccess to the raw pointer. In your case, you don't need it, so don't ask for it. Just skip the whole raw pointer thing and continue living in your safer shared_ptrworld.

另一个原因是它shared_ptr::get()旨在用于您实际上需要访问原始指针的场景。在你的情况下,你不需要它,所以不要要求它。只需跳过整个原始指针的事情,继续生活在您更安全的shared_ptr世界中。

回答by jakar

Ken's answer above(or below, depending on how these are sorted) is great. I don't have enough reputation to comment, otherwise I would.

肯在上面(或下面,取决于它们的排序方式)的回答很棒。我没有足够的声誉发表评论,否则我会。

I'd just like to add that you can also use the ->operator directly on a shared_ptrto access members of the object it points to.

我只想补充一点,您也可以->直接在 a 上使用运算符shared_ptr来访问它指向的对象的成员。

The boost documentationgives a great overview.

升压文件给出了一个很好的概述。

EDIT

编辑

Now that C++11 is widely adopted, std::shared_ptrshould be preferred to the Boost version. See the dereferencing operators here.

现在 C++11 被广泛采用,std::shared_ptr应该优先于 Boost 版本。请参阅此处的取消引用运算符。