unique_ptr::get() 而不是 &* 有什么用? [英] What's with unique_ptr::get() instead of &*?

查看:130
本文介绍了unique_ptr::get() 而不是 &* 有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 unique_ptr 来管理一些资源,以便在任何情况下安全销毁,等等.

I'm using unique_ptr to manage some resources for safe destruction in every circumstance, etc.

void do_something(BLOB* b);
unique_ptr<BLOB> b(new_BLOB(20));

&* 比 get 差很多吗?例如

Is &* much worse than get? e.g.

do_something(&*b);

do_someting(b.get());

两者似乎都有效.

推荐答案

&*b 不一定等同于 b.get().为了确保收到指向托管对象的指针,您需要使用 get().有两个原因:

&*b is not necessarily equivalent to b.get(). In order to be sure to recieve a pointer to the managed object, you want to use get(). There are two reasons:

  • 在不管理任何对象的 unique_ptr 上调用 operator* 是未定义的行为
  • T 类型的托管对象可能会重载 operator&,因此您可能无法收到指向 T 的有效指针.
  • Calling operator* on a unique_ptr not managing any object is undefined behaviour
  • The managed object of type T may overload operator& and as such you may not recieve a valid pointer to T.

标准定义了std::unique_ptroperator*的行为:

typename add_lvalue_reference::type operator*() const;

  1. 要求:get() != nullptr

返回:*get()

因此,如果 get() 返回 nullptr,则不允许应用 operator*(来自 &*)>.

Thus, applying operator* (from &*) is not allowed if get() returns nullptr.

如果存在,您将获得托管对象中任何重载的 operator& 的返回值.这可以通过使用 std::addressof 来规避,但未定义的行为问题仍然存在.

You will get the return value of any overloaded operator& in the managed object if present. This can be circumvented by using std::addressof but the undefined behaviour problem persists.

std::unique_ptr::get() 会给你被管理对象的地址,如果没有对象被管理,nullptr 会给你.使用 get() 更安全,并且结果可预测.

std::unique_ptr<T>::get() will give you the address of the managed object or nullptr if no object is managed. It is safer to use get() and you have a predictable result.

这篇关于unique_ptr::get() 而不是 &amp;* 有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆