std::unique_ptr<T,Deleter>::operator*, std::unique_ptr<T,Deleter>::operator->
来自 cppreference.cn
< cpp | memory | unique ptr
typename std::add_lvalue_reference<T>::type operator*() const noexcept(noexcept(*std::declval<pointer>())); |
(1) | (C++11 起) (C++23 起为 constexpr) |
pointer operator->() const noexcept; |
(2) | (C++11 起) (C++23 起为 constexpr) |
operator* 和 operator-> 提供对 *this 所占有对象的访问。
这些成员函数仅为用于单个对象的 unique_ptr
提供,即主模板。
1) 如果 std::reference_converts_from_temporary_v
<std::add_lvalue_reference_t<T>, decltype(*std::declval<pointer>())> 为 true,那么程序非良构。 |
(C++23 起) |
若 get() 为空指针,则行为未定义。
目录 |
[编辑] 返回值
1) 返回 *this 所占有的对象,等价于 *get()。
2) 返回指向 *this 所占有对象的指针,即 get()。
[编辑] 异常
1) 若
pointer
有抛异常的 operator*,则可能抛出异常。[编辑] 注意
使用 std::add_lvalue_reference 是为了能够实例化 std::unique_ptr<void>,因为 C++ 不允许 void& 而 std::add_lvalue_reference<void> 生成 void。细节见 LWG673。
[编辑] 示例
运行此代码
#include <iostream> #include <memory> struct Foo { void bar() { std::cout << "Foo::bar\n"; } }; void f(const Foo&) { std::cout << "f(const Foo&)\n"; } int main() { std::unique_ptr<Foo> ptr(new Foo); ptr->bar(); f(*ptr); }
输出
Foo::bar f(const Foo&)
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 2762 | C++11 | operator* 可能是潜在抛出的 即使 *get() 是 noexcept |
增加了有条件的 异常规定 |
LWG 4148 | C++23 | 在下列情况下 operator* 可能返回悬垂引用element_type* 与 Deleter::pointer 不同 |
程序格式错误 在这种情况下,枚举是病态的 |
[编辑] 参阅
返回指向托管对象的指针 (公开成员函数) |