C++ Memory Library - static_pointer_cast



Description

It allocates memory for an object of type T using alloc and constructs it passing args to its constructor. The function returns an object of type shared_ptr that owns and stores a pointer to the constructed object.

Declaration

Following is the declaration for std::static_pointer_cast.

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

C++11

template <class T, class U>
   shared_ptr<T> static_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 statically from U* to T*.

Exceptions

noexcep − It doesn't throw any exceptions.

Example

In below example explains about std::static_pointer_cast.

#include <iostream>
#include <memory>

struct BaseClass {};

struct DerivedClass : BaseClass {
   void f() const {
      std::cout << "Sample word!\n";
   }
};
 
int main() {
   std::shared_ptr<BaseClass> ptr_to_base(std::make_shared<DerivedClass>());

   std::static_pointer_cast<DerivedClass>(ptr_to_base)->f();

   static_cast<DerivedClass*>(ptr_to_base.get())->f();

}

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

Sample word!
Sample word!
memory.htm
Advertisements