Namespaces
Variants

std::unique_ptr<T,Deleter>:: operator*, std::unique_ptr<T,Deleter>:: operator->

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
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 ,则程序非良构。
(since 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 类型不同时
此情况下程序
属于病式结构

参见

返回指向被管理对象的指针
(公开成员函数)