unique_ptr::get() 而不是 &* 有什么用? [英] What's with unique_ptr::get() instead of &*?
问题描述
我使用 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 aunique_ptr
not managing any object is undefined behaviour - The managed object of type
T
may overloadoperator&
and as such you may not recieve a valid pointer toT
.
标准定义了std::unique_ptr
的operator*
的行为:
typename add_lvalue_reference
要求:
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
会给你被管理对象的地址,如果没有对象被管理,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() 而不是 &* 有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!