function template
<memory>

std::const_pointer_cast

template <class T, class U>  shared_ptr<T> const_pointer_cast (const shared_ptr<U>& sp) noexcept;
Const cast of shared_ptr
Returns a copy of sp of the proper type with its stored pointer const casted fromU*T*.

If sp is not empty, the returned object shares ownership over sp's resources, increasing by one the use count.

If sp is empty, the returned object is an empty shared_ptr.

该函数只能转换满足以下表达式有效的类型
1
const_cast<T*>(sp.get())

参数

sp
A shared_pointer.
U*应可转换为T*usingconst_cast.

返回值

A shared_ptr object that owns the same pointer as sp (if any) and has a shared pointer that points to the same object as sp with a potentially different const-qualification.

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// static_pointer_cast example
#include <iostream>
#include <memory>

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

  foo = std::make_shared<int>(10);

  bar = std::const_pointer_cast<const int>(foo);

  std::cout << "*bar: " << *bar << '\n';
  *foo = 20;
  std::cout << "*bar: " << *bar << '\n';

  return 0;
}

输出
*bar: 10
*bar: 20


另见