const std::shared_ptr<int> sharedPtr = std::make_shared<int>(42); //将const std::shared_ptr<int>转换为std::shared_ptr<int> std::shared_ptr<int> nonConstSharedPtr = const_cast<std::shared_ptr<int>>(sharedPtr); //将std::shared_ptr<const int>转换为std::shared_ptr<int> const ...
它们的功能和std::static_cast()、std::dynamic_cast、std::const_cast()和std::reinterpret_cast()类似,只不过转换的是智能指针std::shared_ptr,返回的也是std::shared_ptr类型。 1、std::static_pointer_cast():当指针是智能指针时候,向上转换,用static_cast 则转换不了,此时需要使用static_pointer_cast。
template <class Ty, class Other> shared_ptr<Ty> const_pointer_cast(const shared_ptr<Other>& sp); 参数 Ty 返回的共享指针控制的类型。 Other 参数控制的类型共享指针。 Other 共享指针参数。 备注 模板函数的情况下返回空 const_cast<Ty*>(sp.get()) 对象是否返回 null 指针;否则返回的资源由 spsha...
typedef shared_ptr<int> int_ptr; typedef shared_ptr<const int> const_int_ptr; int main(void) { const_int_ptr Ckk(new int(1)); assert(Ckk.use_count() == 1); cout << "Ckk = " << *Ckk << endl; int_ptr kk = const_pointer_cast<int>(Ckk); // obtain a 2nd reference *kk...
shared_ptr<int> func(const shared_ptr<int> &ptr) { *ptr += 1; return ptr; } 这里的const shared_ptr<int> &ptr和常规的const T &p一样,这里的const都是顶层const,也就是说我们不能改变ptr的地址,也不能改变p的值。 常规的内置指针和const有以下组合: ...
否则,新的 shared_ptr 将与r 的初始值共享所有权,但若 dynamic_pointer_cast 所进行的 dynamic_cast 返回空指针,则它为空。 令Y 为typename std::shared_ptr<T>::element_type,则将分别通过求值下列表达式,获得所得 std::shared_ptr 的存储指针: 1,2) static_cast<Y*>(r.get())...
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> ...
引用std::string对象的(唯一的)std::shared_ptr示例只存在于函数作用域的末尾,但是原始指针值的存在...
std::shared_ptr其存储的指针是从r%27s使用强制转换表达式存储指针。如果r是空的,新的也是空的shared_ptr%28但其存储的指针不一定为空%29。 否则,新的shared_ptr将与r,但如果dynamic_cast由dynamic_pointer_cast返回空指针。 让Y成typenamestd::shared_ptr<T>::element_type,然后产生的std::shared_ptr%27s...
C:const_cast转换 const_cast用于去除类型的const限定符。主要用于指针或引用类型。 #include<iostream>intmain(){constinti=42;int*p=const_cast<int*>(&i);// const_cast:去除const*p=21;// 修改const变量的值(未定义行为)std::cout<<"int: "<<i<<", int through pointer: "<<*p<<std::endl;retu...