function template
<memory>

std::static_pointer_cast

template <class T, class U>  shared_ptr<T> static_pointer_cast (const shared_ptr<U>& sp) noexcept;
shared_ptr 的靜態轉換
返回一個指向其 儲存指標 被靜態轉換後的正確型別的 sp 的副本U*T*.

如果 sp 非空,則返回的物件共享 sp 的資源,其 使用計數 會加一。

如果 sp 為空,則返回的物件是一個空的 shared_ptr

該函式只能轉換滿足以下表達式有效的型別
1
static_cast<T*>(sp.get())

引數

sp
一個 shared_pointer
U*應可轉換為T*usingstatic_cast.

返回值

一個 shared_ptr 物件,它擁有與 sp 相同的指標(如果有),並且其 共享指標 指向與 sp 相同的物件,但型別可能不同。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// static_pointer_cast example
#include <iostream>
#include <memory>

struct A {
  static const char* static_type;
  const char* dynamic_type;
  A() { dynamic_type = static_type; }
};
struct B: A {
  static const char* static_type;
  B() { dynamic_type = static_type; }
};

const char* A::static_type = "class A";
const char* B::static_type = "class B";

int main () {
  std::shared_ptr<A> foo;
  std::shared_ptr<B> bar;

  foo = std::make_shared<A>();

  // cast of potentially incomplete object, but ok as a static cast:
  bar = std::static_pointer_cast<B>(foo);

  std::cout << "foo's static  type: " << foo->static_type << '\n';
  std::cout << "foo's dynamic type: " << foo->dynamic_type << '\n';
  std::cout << "bar's static  type: " << bar->static_type << '\n';
  std::cout << "bar's dynamic type: " << bar->dynamic_type << '\n';

  return 0;
}

輸出
foo's static  type: class A
foo's dynamic type: class A
bar's static  type: class B
bar's dynamic type: class A


另見