C++基类和派生类的智能指针转换:static_pointer_cast、dynamic_pointer_cast、const_pointer_cast、reinterpret_pointer_cast

当我们用“裸”指针进行类层次上的上下行转换时,可以使用dynamic_cast。当然我们也可以使用static_cast,只是dynamic_cast在进行下行转换的时候(即基类到派生类)具有类型检查功能,而static_cast没有。因此存在安全问题。

当我们使用智能指针时,如果需要进行类层次上的上下行转换时,可以使用std::static_pointer_cast()、std::dynamic_pointer_cast、std::const_pointer_cast()和std::reinterpret_pointer_cast()。它们的功能和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。

2、std::dynamic_pointer_cast():当指针是智能指针时候,向下转换,用dynamic_cast 则转换不了,此时需要使用dynamic_pointer_cast。

3、std::const_pointer_cast():功能与std::const_cast()类似

4、std::reinterpret_pointer_cast():功能与std::reinterpret_cast()类似

Defined in header <memory>

   

template< class T, class U >
std::shared_ptr<T> static_pointer_cast( const std::shared_ptr<U>& r ) noexcept;

(1) (since C++11)

template< class T, class U >
std::shared_ptr<T> static_pointer_cast( std::shared_ptr<U>&& r ) noexcept;

(2) (since C++20)

template< class T, class U >
std::shared_ptr<T> dynamic_pointer_cast( const std::shared_ptr<U>& r ) noexcept;

(3) (since C++11)

template< class T, class U >
std::shared_ptr<T> dynamic_pointer_cast( std::shared_ptr<U>&& r ) noexcept;

(4) (since C++20)

template< class T, class U >
std::shared_ptr<T> const_pointer_cast( const std::shared_ptr<U>& r ) noexcept;

(5) (since C++11)

template< class T, class U >
std::shared_ptr<T> const_pointer_cast( std::shared_ptr<U>&& r ) noexcept;

(6) (since C++20)

template< class T, class U >
std::shared_ptr<T> reinterpret_pointer_cast( const std::shared_ptr<U>& r ) noexcept;

(7) (since C++17)

template< class T, class U >
std::shared_ptr<T> reinterpret_pointer_cast( std::shared_ptr<U>&& r ) noexcept;

(8) (since C++20)

基类和派生类的智能指针转换要使用std::dynamic_pointer_caststd::static_pointer_cast。由于std::dynamic_pointer_castdynamic_cast原理一样,std::static_pointer_caststatic_cast原理一样

Creates a new instance of std::shared_ptr whose stored pointer is obtained from r's stored pointer using a cast expression.

If r is empty, so is the new shared_ptr (but its stored pointer is not necessarily null). Otherwise, the new shared_ptr will share ownership with the initial value of r, except that it is empty if the dynamic_cast performed by dynamic_pointer_cast returns a null pointer.

Let Y be typename std::shared_ptr<T>::element_type, then the resulting std::shared_ptr's stored pointer will be obtained by evaluating, respectively:

1-2) static_cast<Y*>(r.get()).

3-4) dynamic_cast<Y*>(r.get()) (If the result of the dynamic_cast is a null pointer value, the returned shared_ptr will be empty.)

5-6) const_cast<Y*>(r.get()).

7-8) reinterpret_cast<Y*>(r.get())

The behavior of these functions is undefined unless the corresponding cast from U* to T* is well formed:

1-2) The behavior is undefined unless static_cast<T*>((U*)nullptr) is well formed.

3-4) The behavior is undefined unless dynamic_cast<T*>((U*)nullptr) is well formed.

5-6) The behavior is undefined unless const_cast<T*>((U*)nullptr) is well formed.

7-8) The behavior is undefined unless reinterpret_cast<T*>((U*)nullptr) is well formed.

After calling the rvalue overloads (2,4,6,8), r is empty and r.get() == nullptr, except that r is not modified for dynamic_pointer_cast (4) if the dynamic_cast fails.

(since C++20)

Parameters

r - The pointer to convert

Notes

The expressions std::shared_ptr<T>(static_cast<T*>(r.get())), std::shared_ptr<T>(dynamic_cast<T*>(r.get())) and std::shared_ptr<T>(const_cast<T*>(r.get())) might seem to have the same effect, but they all will likely result in undefined behavior, attempting to delete the same object twice!

Possible implementation

1、std::static_pointer_cast():

template< class T, class U >
std::shared_ptr<T> static_pointer_cast( const std::shared_ptr<U>& r ) noexcept
{auto p = static_cast<typename std::shared_ptr<T>::element_type*>(r.get());return std::shared_ptr<T>(r, p);
}
2、std::dynamic_pointer_cast()
template< class T, class U >
std::shared_ptr<T> dynamic_pointer_cast( const std::shared_ptr<U>& r ) noexcept
{if (auto p = dynamic_cast<typename std::shared_ptr<T>::element_type*>(r.get())) {return std::shared_ptr<T>(r, p);} else {return std::shared_ptr<T>();}
}

3、std::const_pointer_cast()

template< class T, class U >
std::shared_ptr<T> const_pointer_cast( const std::shared_ptr<U>& r ) noexcept
{auto p = const_cast<typename std::shared_ptr<T>::element_type*>(r.get());return std::shared_ptr<T>(r, p);
}

4、std::reinterpret_pointer_cast()

template< class T, class U >
std::shared_ptr<T> reinterpret_pointer_cast( const std::shared_ptr<U>& r ) noexcept
{auto p = reinterpret_cast<typename std::shared_ptr<T>::element_type*>(r.get());return std::shared_ptr<T>(r, p);
}

使用示例:

#include <iostream>
#include <memory>struct Base
{ int a; virtual void f() const { std::cout << "I am base!\n";}virtual ~Base(){}
};struct Derived : Base
{void f() const override{ std::cout << "I am derived!\n"; }~Derived(){}
};int main(){auto basePtr = std::make_shared<Base>();std::cout << "Base pointer says: ";basePtr->f();auto derivedPtr = std::make_shared<Derived>();std::cout << "Derived pointer says: ";derivedPtr->f();// static_pointer_cast to go up class hierarchybasePtr = std::static_pointer_cast<Base>(derivedPtr);std::cout << "Base pointer to derived says: ";basePtr->f();// dynamic_pointer_cast to go down/across class hierarchyauto downcastedPtr = std::dynamic_pointer_cast<Derived>(basePtr);if(downcastedPtr){ std::cout << "Downcasted pointer says: ";downcastedPtr->f(); }// All pointers to derived share ownershipstd::cout << "Pointers to underlying derived: " << derivedPtr.use_count() << "\n";
}

Output:

Base pointer says: I am base!
Derived pointer says: I am derived!
Base pointer to derived says: I am derived!
Downcasted pointer says: I am derived!
Pointers to underlying derived: 3

示例2

#include <iostream> // std::cout std::endl
#include <memory> // std::shared_ptr std::dynamic_pointer_cast std::static_pointer_castclass base
{
public:virtual ~base(void) = default;
};class derived : public base
{
};class test : public base
{
};int main(void)
{std::cout << std::boolalpha;// 两个不同的派生类对象auto derivedobj = std::make_shared<derived>();auto testobj = std::make_shared<test>();// 隐式转换 derived->basestd::shared_ptr<base> pointer1 = derivedobj;// static_pointer_cast derived->baseauto pointer2 = std::static_pointer_cast<base>(derivedobj);// dynamic_pointer_cast base->derivedauto pointer3 = std::dynamic_pointer_cast<derived>(pointer1);std::cout << (pointer3 == nullptr) << std::endl;// dynamic_pointer_cast base->derivedauto pointer4 = std::dynamic_pointer_cast<test>(pointer1);std::cout << (pointer4 == nullptr) << std::endl;return 0;
}

输出结果:

false
true

std::reinterpret_pointer_cast()和std::const_pointer_cast()示例:

#include <memory>
#include <cassert>
#include <cstdint>int main()
{std::shared_ptr<int> foo;std::shared_ptr<const int> bar;foo = std::make_shared<int>(10);bar = std::const_pointer_cast<const int>(foo);std::cout << "*bar: " << *bar << std::endl;*foo = 20;std::cout << "*bar: " << *bar << std::endl;std::shared_ptr<std::int8_t[]> p(new std::int8_t[4]{1, 1, 1, 1});std::shared_ptr<std::int32_t[]> q = std::reinterpret_pointer_cast<std::int32_t[]>(p);std::int32_t r = q[0];std::int32_t x = (1 << 8) | (1 << 16) | (1 << 24) | 1;assert(r == x);return 0;
}

输出:

*bar: 10
*bar: 20
Press <RETURN> to close this window...

c++智能指针转化:static_pointer_cast、dynamic_pointer_cast、const_pointer_cast、reinterpret_pointer_cast相关推荐

  1. 普通指针到智能指针的转换

    普通指针到智能指针的转换 int* iPtr = new int(42); shared_ptr<int> p(iPtr); 智能指针到普通指针的转换 int* pI = p.get(); ...

  2. C++ 智能指针(unique_ptr / shared_ptr)代码实现

    文章目录 unique_ptr 智能指针的实现 shared_ptr 智能指针的实现 指针类型转换 unique_ptr 智能指针的实现 一个对象只能被单个unique_ptr 所拥有. #inclu ...

  3. 现代C++之手写智能指针

    现代C++之手写智能指针 0.回顾 所有代码还是放在仓库里面,欢迎star! https://github.com/Light-City/CPlusPlusThings 前面一节编写了一个RAII的例 ...

  4. STL(五)之智能指针剖析

    C++标准库(五)之智能指针源码剖析 _Mutex_base template<_Lock_policy _Lp> class _Mutex_base { protected: enum ...

  5. C++智能指针:TR1的 shared_ptr 和 weak_ptr 使用介绍

    (所有示例的运行,将#序号所在main()函数去掉序号即可,参考[url]http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c15361/ ...

  6. 关于智能指针shared_ptr

    How to: Create and Use shared_ptr instances shared_ptr 类型是 C++ 标准库中的一种智能指针,专为多个所有者可能必须管理内存中对象的生命周期的情 ...

  7. C/C++编程:智能指针

    计算机系统中的资源有很多种,内存是我们最常用到的,此外还有文件描述符,socket.操作系统handler,数据库连接等,程序里申请这些资源之后必须及时归坏系统,否则就会产生难以预料的后果 std:: ...

  8. Boost库基础-智能指针(intrusive_ptr)

    intrusive_ptr intrusive_ptr是一种引用计数型智能指针,与之前介绍的scoped_ptr.shared_ptr不同,需要额外增加一些的代码才能使用. 如果现存代码已经有了引用计 ...

  9. 五点讲述C++智能指针的点点滴滴

    (在学习C/C++或者想要学习C/C++可以加我们的学习交流QQ群:712263501群内有相关学习资料) 0.摘要 本文先讲了智能指针存在之前C++面临的窘境,并顺理成章地引出利用RAII技术封装普 ...

  10. C++ 智能指针详解

    智能指针内容很多,重点是基本用法. #include <boost/shared_ptr.hpp> class CBase: public boost::enable_shared_fro ...

最新文章

  1. swift 错误集合 ------持续更新中
  2. svg图片怎么存手机上_一张普通的图片,是怎么让安卓手机死机的?
  3. 共享数字经济之光!世界互联网大会重磅发布“30位新生代数字经济人才”
  4. addcslashes php 有什么用处,PHP addcslashes函数有什么用
  5. python截取子串_python获得子串
  6. Ubuntu14.04 kylin 安装配置Tomcat7服务器
  7. android app.build文件_网易友品 Android 客户端组件化演进
  8. Redis- 内存数据库Redis之安装部署
  9. GAN实现半监督学习
  10. 文件操作函数(读写)
  11. java的基础类型和字节大小_java的基础类型和字节大小
  12. JQuery中的一些重要方法
  13. 技术开发频道一周精选2007-8-3
  14. [Python] 生成迭代器 iter() 函数
  15. u8显示云服务器已离线_u8登录不知道这样的主机
  16. 信号与系统研讨(一)匹配滤波器
  17. 软件推荐:论文翻译阅读 + 文献管理 + markdown笔记 + 多设备同步 + 一键导出bib参考文献
  18. 2019最新PHP100项目实战(PHP新手入门教程)
  19. PHP加密如何保护php源码不被破解不被轻易去授权
  20. @人生随笔:一年一影帝,百年周星驰

热门文章

  1. 为什么泛型类的类型不能是基本数据类型
  2. python中写公式_使用Python书写的公式编辑器
  3. linux 开发面试---基础题1
  4. 国际知名芯片专家,加盟武昌理工学院人工智能学院
  5. Mermaid制作甘特图
  6. zblog火车头采集经验
  7. 「镁客·请讲」中科云创周北川:从数据到云端,我们要上下打通工业物联网产业链...
  8. Frame Bounds 区别
  9. 【DVB】【Cert】DVD相关认证简介
  10. android游戏备份农场,zynga旗下的虚拟农场farmville将正式进入android平台