unique_ptr :: get()而不是&*是什么?

Sam*_*ott 6 c++ pointers smart-pointers unique-ptr

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

void do_something(BLOB* b);
unique_ptr<BLOB> b(new_BLOB(20));
Run Code Online (Sandbox Code Playgroud)

&*不是变得更糟?例如

do_something(&*b);
Run Code Online (Sandbox Code Playgroud)

要么

do_someting(b.get());
Run Code Online (Sandbox Code Playgroud)

两者似乎都有效.

Nat*_*ica 13

如果没有内存归属于将返回的内容operator*,则std::unique_ptr具有未定义的行为.unique_ptrget()nullptr

如果unique_ptr可能是空的我建议使用get()否则没有区别.


Pix*_*ist 9

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

  • 调用operator*一个unique_ptr没有管理任何对象是不确定的行为
  • 类型的托管对象T可能会重载operator&,因此您可能无法接收到有效的指针T.

该标准定义了以下operator*方面std::unique_ptr:

typename add_lvalue_reference<T>::type operator*() const;

  1. 要求: get() != nullptr

  2. 返回: *get()

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

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

std::unique_ptr<T>::get()将为您提供托管对象的地址,或者nullptr是否管理对象.它使用起来更安全,get()并且您可以获得可预测的结果.