跳到主要内容

std::shared_ptr<T>::operator*, std::shared_ptr<T>::operator->

声明

C++11
// 1)
T& operator*() const noexcept;
// 2)
T* operator->() const noexcept;

解引用存储的指针。如果存储的指针为null,则行为未定义。

参数

(无)

返回值


解引用存储的指针的结果,即*get()
2)
存储的指针,即get()

备注

T是(可能带有 cv 限定的)void时,函数(1)是否声明是未指定的。

T是数组类型时,这些成员函数是否声明以及它们的返回类型是什么是未指定的,但这些函数的声明(不一定是定义)是良构的(自 C++17 起)。

如果尽管未指定但声明了任何一个函数,那么它的返回类型是未指定的,但保证该函数的声明(尽管不一定是定义)是合法的。这使得可以实例化std::shared_ptr<void>

示例

#include <iostream>
#include <memory>

struct Foo
{
Foo(int in) : a(in) {}
void print() const
{
std::cout
<< "a = " << a << '\n';
}
int a;
};

int main()
{
auto ptr = std::make_shared<Foo>(10);
ptr->print();
(*ptr).print();
}
结果
a = 10
a = 10

std::shared_ptr<T>::operator*, std::shared_ptr<T>::operator->

声明

C++11
// 1)
T& operator*() const noexcept;
// 2)
T* operator->() const noexcept;

解引用存储的指针。如果存储的指针为null,则行为未定义。

参数

(无)

返回值


解引用存储的指针的结果,即*get()
2)
存储的指针,即get()

备注

T是(可能带有 cv 限定的)void时,函数(1)是否声明是未指定的。

T是数组类型时,这些成员函数是否声明以及它们的返回类型是什么是未指定的,但这些函数的声明(不一定是定义)是良构的(自 C++17 起)。

如果尽管未指定但声明了任何一个函数,那么它的返回类型是未指定的,但保证该函数的声明(尽管不一定是定义)是合法的。这使得可以实例化std::shared_ptr<void>

示例

#include <iostream>
#include <memory>

struct Foo
{
Foo(int in) : a(in) {}
void print() const
{
std::cout
<< "a = " << a << '\n';
}
int a;
};

int main()
{
auto ptr = std::make_shared<Foo>(10);
ptr->print();
(*ptr).print();
}
结果
a = 10
a = 10