1. 解释std::static_pointer_cast的基本概念 std::static_pointer_cast 是C++11 引入的一个模板函数,用于智能指针(如 std::shared_ptr 或std::weak_ptr)之间的类型转换。这种转换是编译时的强制转换,不会在运行时进行检查,类似于 static_cast,但专门用于智能指针,确保转换后的指针仍然保留智能指针的内存管理功能...
不用std::static_pointer_cast // static_pointer_cast example #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 = sta...
(); // 沿类层次向上的 static_pointer_cast basePtr = std::static_pointer_cast<Base>(derivedPtr); std::cout << "指向派生类的基类指针说: "; basePtr->f(); // 沿类层次向下/跨类层次的 dynamic_pointer_cast auto downcastedPtr = std::dynamic_pointer_cast<Derived>(basePtr); if (down...
std::shared_ptr<T> static_pointer_cast( const std::shared_ptr<U>& r ) noexcept; (1) (C++11 起) template< class T, class U >std::shared_ptr<T> static_pointer_cast( std::shared_ptr<U>&& r ) noexcept; (2) (C++20 起) template< class T, class U >std::shared_ptr<T> ...
示例代码: int num = 10; double convertedNum = static_cast(num); Base* basePtr = newDerived(); Derived...当转换的目标类型为指针时,如果转换失败,dynamic_cast会返回空指针;当转换的目标类型为引用时,如果转换失败,...
《C++面向对象程序设计》✍千处细节、万字总结(建议收藏)「建议收藏」
r-the pointer to convert Notes The expressionsstd::shared_ptr<T>(static_cast<T*>(r.get())),std::shared_ptr<T>(dynamic_cast<T*>(r.get()))andstd::shared_ptr<T>(const_cast<T*>(r.get()))might seem to have the same effect, but they all will likely result in undefined behavior...