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 from U* to 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.

The function can only cast types for which the following expression would be valid:
 
const_cast<T*>(sp.get())


Parameters

sp
A shared_pointer.
U* shall be convertible to T* using const_cast.

Return Value

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.

Example

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;
}


Output:
*bar: 10
*bar: 20

See also