如何获取共享指针所指向的对象?
我有一个疑问。我们可以直接获取共享指针指向的对象吗?或者我们应该通过get()
调用获取底层RAW指针,然后访问相应的对象?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您有两种选择来检索对
shared_ptr
所指向的对象的引用。假设您有一个名为ptr
的shared_ptr
变量。您可以使用*ptr
或*ptr.get()
获取引用。这两个应该是等效的,但首选第一个。这样做的原因是您实际上是在尝试模仿原始指针的取消引用操作。表达式
*ptr
的意思是“获取ptr
指向的数据”,而表达式*ptr.get()
则为“Get me the包装在ptr
内的原始指针指向的数据”。显然,第一个更清楚地描述了您的意图。另一个原因是
shared_ptr::get()
旨在用于您实际上需要访问原始指针的场景。就您而言,您不需要它,所以不要要求它。只需跳过整个原始指针的事情并继续生活在更安全的shared_ptr
世界中。You have two options to retrieve a reference to the object pointed to by a
shared_ptr
. Suppose you have ashared_ptr
variable namedptr
. You can get the reference either by using*ptr
or*ptr.get()
. These two should be equivalent, but the first would be preferred.The reason for this is that you're really attempting to mimic the dereference operation of a raw pointer. The expression
*ptr
reads "Get me the data pointed to byptr
", whereas the expression*ptr.get()
"Get me the data pointed to by the raw pointer which is wrapped insideptr
". Clearly, the first describes your intention much more clearly.Another reason is that
shared_ptr::get()
is intended to be used in a scenario where you actually need access 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 safershared_ptr
world.上面是 Ken 的回答 (或低于,取决于它们的排序方式)很棒。我没有足够的声誉来发表评论,否则我会的。
我想补充一点,您还可以直接在
shared_ptr
上使用->
运算符来访问它指向的对象的成员。Boost 文档提供了很好的概述。
编辑
现在C++11被广泛采用,
std::shared_ptr
应该优先于 Boost 版本。请参阅此处取消引用运算符。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 ashared_ptr
to access members of the object it points to.The boost documentation gives a great overview.
EDIT
Now that C++11 is widely adopted,
std::shared_ptr
should be preferred to the Boost version. See the dereferencing operators here.