C++ Memory Library - dynamic_pointer_cast



Description

It returns a copy of sp of the proper type with its stored pointer casted dynamically from U* to T*.

Declaration

Following is the declaration for std::dynamic_pointer_cast.

template <class T, class U>
  shared_ptr<T> dynamic_pointer_cast (const shared_ptr<U>& sp) noexcept;

C++11

template <class T, class U>
  shared_ptr<T> dynamic_pointer_cast (const shared_ptr<U>& sp) noexcept;

Parameters

sp − Its a shared pointer.

Return Value

It returns a copy of sp of the proper type with its stored pointer casted dynamically from U* to T*.

Exceptions

noexcep − It doesn't throw any exceptions.

Example

In below example explains about std::dynamic_pointer_cast.

#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 = "sample text A";
const char* B::static_type = "sample text B";

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

   bar = std::make_shared<B>();

   foo = std::dynamic_pointer_cast<A>(bar);

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

Let us compile and run the above program, this will produce the following result −

foo's static type: sample text A
foo's dynamic type: sample text B
bar's static type: sample text B
bar's dynamic type: sample text B
memory.htm
Advertisements