• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

    最終更新日時(UTC):
    が更新

    履歴 編集

    function template
    <memory>

    std::static_pointer_cast

    namespace std {
      template<class T, class U>
      shared_ptr<T> static_pointer_cast(const shared_ptr<U>& r) noexcept; // (1) C++11
    
      template <class T, class U>
      shared_ptr<T> static_pointer_cast(shared_ptr<U>&& r) noexcept;      // (2) C++20
    }
    

    概要

    shared_ptr で管理するインスタンスに対して static_cast を行う。

    戻り値

    • r が空であった場合、この関数は空の shared_ptr<T> を返却する。
    • (1) :

      return shared_ptr<T>(r, static_cast<typename shared_ptr<T>::element_type*>(r.get()));
      

    • (2) :

      return shared_ptr<T>(std::move(r), static_cast<typename shared_ptr<T>::element_type*>(r.get()));
      

    備考

    • shared_ptr<T>(static_cast<T*>(r.get())) という方法は未定義動作を引き起こすので使用しないこと。

    #include <memory>
    #include <iostream>
    
    struct A {
      virtual void call() const {
        std::cout << "A::call" << std::endl;
      }
    };
    
    struct B : A {
      void call() const {
        std::cout << "B::call()" << std::endl;
      }
    };
    
    int main() {
      auto sp1 = std::make_shared<B>();
      sp1->call();
    
      auto sp2 = std::static_pointer_cast<A>(sp1);
      if(sp1 == sp2) {
        sp2->call();
      }
    }
    

    出力

    B::call()
    B::call()
    

    バージョン

    言語

    • C++11

    処理系

    参照