C++三剑客之std::any(二) : 源码剖析

2024-05-24 06:52
文章标签 c++ 源码 剖析 std 三剑客

本文主要是介绍C++三剑客之std::any(二) : 源码剖析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

1.引言

2.std::any的存储分析

3._Any_big_RTTI与_Any_small_RTTI

4.std::any的构造函数

4.1.从std::any构造

4.2.可变参数模板构造函数

4.3.赋值构造与emplace函数

5.reset函数

6._Cast函数

7.make_any模版函数

8.std::any_cast函数

9.总结


1.引言

 C++三剑客之std::any(一) : 使用详解_c++ std::any-CSDN博客

        在前面详细的讲解了std::any的用法,std::any能够容纳任何可拷贝构造类型的数据,我们不禁会想它是怎么做到的呢?不同类型怎么做到巧妙的构造与转换的?多种构造函数如何实现?内部数据怎么储存?为什么分Big,Samll,trivial?

        下面就以vs2019的std::any实现为例进行具体分析它的实现。

2.std::any的存储分析

std::any 将保存内容的内存形式分为了三种:_Small_Trivial_Big

划分规则代码为:

// size in pointers of std::function and std::any (roughly 3 pointers larger than std::string when building debug)
constexpr int _Small_object_num_ptrs = 6 + 16 / sizeof(void*); //64位系统: 8//64位系统:_Any_trivial_space_size = 56
inline constexpr size_t _Any_trivial_space_size = (_Small_object_num_ptrs - 1) * sizeof(void*);template <class _Ty>
inline constexpr bool _Any_is_trivial = alignof(_Ty) <= alignof(max_align_t)&& is_trivially_copyable_v<_Ty> && sizeof(_Ty) <= _Any_trivial_space_size;//64位系统:_Any_small_space_size = 48
inline constexpr size_t _Any_small_space_size = (_Small_object_num_ptrs - 2) * sizeof(void*);template <class _Ty>
inline constexpr bool _Any_is_small = alignof(_Ty) <= alignof(max_align_t)&& is_nothrow_move_constructible_v<_Ty> && sizeof(_Ty) <= _Any_small_space_size;

简单来说,满足 _Any_is_trivial 则为 Trivial 类型内存,满足 _Any_is_small 则为 Small 类型内存,其余的则为 Big 类型内存。

在 64 位系统下,划分规则可以解释为:

  • _Any_is_small:类型长度小于等于 48 字节,内存对齐长度小于等于 8 字节,拥有具备 nothrow 声明的移动构造
  • _Any_is_trivial:类型长度小于等于 56 字节,内存对齐长度小于等于 8 字节,可平凡拷贝(基本数据类型、可平凡拷贝的聚合类型、以上类型的数组等)

下面是一些 _Any_is_small_Any_is_trivial 判断的实测值:

struct Test1 {char a[48];
};struct Test2 {char a[56];
};struct Test3 {Test3(Test3&& other){memcpy(a, other.a, sizeof(Test3));}char a[48] {};
};struct Test4 {int& a;
};struct Test5 {virtual void a() = 0;
};// 1
std::cout << std::_Any_is_small<char> << std::endl;
// 1
std::cout << std::_Any_is_small<int> << std::endl;
// 1
std::cout << std::_Any_is_small<double> << std::endl;
// 1
std::cout << std::_Any_is_small<Test1> << std::endl;
// 0, sizeof(Test2) > _Any_trivial_space_size
std::cout << std::_Any_is_small<Test2> << std::endl;
// 0, is_nothrow_move_constructible_v<_Ty> == false
std::cout << std::_Any_is_small<Test3> << std::endl;
// 1
std::cout << std::_Any_is_small<Test4> << std::endl;
// 0, is_nothrow_move_constructible_v<_Ty> == false
std::cout << std::_Any_is_small<Test5> << std::endl;// 1
std::cout << std::_Any_is_trivial<char> << std::endl;
// 1
std::cout << std::_Any_is_trivial<int> << std::endl;
// 1
std::cout << std::_Any_is_trivial<double> << std::endl;
// 1
std::cout << std::_Any_is_trivial<Test1> << std::endl;
// 1
std::cout << std::_Any_is_trivial<Test2> << std::endl;
// 0, is_trivially_copyable_v == false
std::cout << std::_Any_is_trivial<Test3> << std::endl;
// 1
std::cout << std::_Any_is_trivial<Test4> << std::endl;
// 0, is_trivially_copyable_v == false
std::cout << std::_Any_is_trivial<Test5> << std::endl;

 下面看看3中模型的数据存储结构

    //【1】struct _Small_storage_t {unsigned char _Data[_Any_small_space_size];const _Any_small_RTTI* _RTTI;};static_assert(sizeof(_Small_storage_t) == _Any_trivial_space_size);//【2】struct _Big_storage_t {// Pad so that _Ptr and _RTTI might share _TypeData's cache lineunsigned char _Padding[_Any_small_space_size - sizeof(void*)];void* _Ptr;const _Any_big_RTTI* _RTTI;};static_assert(sizeof(_Big_storage_t) == _Any_trivial_space_size);//【3】struct _Storage_t {union {unsigned char _TrivialData[_Any_trivial_space_size];_Small_storage_t _SmallStorage;_Big_storage_t _BigStorage;};uintptr_t _TypeData;};static_assert(sizeof(_Storage_t) == _Any_trivial_space_size + sizeof(void*));static_assert(is_standard_layout_v<_Storage_t>);union {_Storage_t _Storage{};max_align_t _Dummy;};

我们可以看出_Storage_t本身由于一个联合体加上uintptr_t类型的_TypeData,在64位下uintptr_t就是unsigned long long,32位 unsigned int;

  • _TypeData,这个实际是MSVC自己实现的,为了方便类型区分,借助了编译器内部类型信息。其什为:_Storage._TypeData = reinterpret_cast<uintptr_t>(&typeid(_Decayed)) | static_cast<uintptr_t>(_Any_representation::_Trivial);其中_Decayed为any要储存类型的模板退化类型,然后用typeid求出std::type_info全局静态类型再取地址,用reinterpret_cast强转,说来说去就是为了类型得到一个类似hash后的数值,这里只是地址,然后再|上_Any_representation枚举值,为了后面来区分类型。
    • enum class _Any_representation : uintptr_t { _Trivial, _Big, _Small }; 类型也比较容易,平凡类对应数值0,大类1,小类2
    • typeid返回type_info这个实现,实际上没有编译器内部实现也可以自己模板实现,模板类有个int型静态常量成员,对类型进行特化,最后也是取地址即可。
    • 为什么_TypeData敢直接或上枚举,因为type_info的大小肯定大于3,两个type_info就算连续存储地址差肯定大于4,所以就算|2的话,从hash角度够用,也不会引发错误。
  • _TrivialData[_Any_trivial_space_size];为char数组,其中inline constexpr size_t _Any_trivial_space_size = (_Small_object_num_ptrs - 1) * sizeof(void*);,编译器常量,只要求_Small_object_num_ptrs即可,_Small_object_num_ptrs它又是typeinfo文件中的编译期常量,constexpr int _Small_object_num_ptrs = 6 + 16 / sizeof(void*);,对于64位也就是8,那么可以得出_Any_trivial_space_size为56,所以就是大小为char[56]
  • _Small_storage_t;是一个结构体,先是char数组且大小为_Any_small_space_size,这个也是编译期常理,inline constexpr size_t _Any_small_space_size = (_Small_object_num_ptrs - 2) * sizeof(void*);由上面可以就是6* 8 = 48;然后接一个_Any_small_RTTI指针,也是8,大小总共一起还是56
  • _Big_storage_t;也是一个结构体,先是char数组且大小为_Any_small_space_size - sizeof(void*),这由上面可以就是48 - 8 = 40;再接一个8字节void*指针,最后接一个_Any_big_RTTI指针,也是8,大小总共一起还是56

综上可以看出:_Storage_t就是56+8 = 64字节大小,我们对any进行sizeof得到的结果也是64,印证分析,只不过具体一个any的对象是union中三个类型中的一个。

3._Any_big_RTTI与_Any_small_RTTI

Trivial 类型的内存是直接对拷的,对于这种内存无需再添加额外的生命周期指针。按照 Small 内存的定义,对于 Small 内存要添加 in_place 的销毁、拷贝、移动函数指针,而 Big 则需要保存堆内存的拷贝与销毁函数指针。源码中定义了 _Any_small_RTTI_Any_big_RTTI 结构体,来存储这些指针:

struct _Any_big_RTTI { // Hand-rolled vtable for types that must be heap allocated in an anyusing _Destroy_fn = void __CLRCALL_PURE_OR_CDECL(void*) _NOEXCEPT_FNPTR;using _Copy_fn    = void* __CLRCALL_PURE_OR_CDECL(const void*);template <class _Ty>static void __CLRCALL_PURE_OR_CDECL _Destroy_impl(void* const _Target) noexcept {::delete static_cast<_Ty*>(_Target);}template <class _Ty>_NODISCARD static void* __CLRCALL_PURE_OR_CDECL _Copy_impl(const void* const _Source) {return ::new _Ty(*static_cast<const _Ty*>(_Source));}_Destroy_fn* _Destroy;_Copy_fn* _Copy;
};struct _Any_small_RTTI { // Hand-rolled vtable for nontrivial types that can be stored internally in an anyusing _Destroy_fn = void __CLRCALL_PURE_OR_CDECL(void*) _NOEXCEPT_FNPTR;using _Copy_fn    = void __CLRCALL_PURE_OR_CDECL(void*, const void*);using _Move_fn    = void __CLRCALL_PURE_OR_CDECL(void*, void*) _NOEXCEPT_FNPTR;template <class _Ty>static void __CLRCALL_PURE_OR_CDECL _Destroy_impl(void* const _Target) noexcept {_Destroy_in_place(*static_cast<_Ty*>(_Target));}template <class _Ty>static void __CLRCALL_PURE_OR_CDECL _Copy_impl(void* const _Target, const void* const _Source) {_Construct_in_place(*static_cast<_Ty*>(_Target), *static_cast<const _Ty*>(_Source));}template <class _Ty>static void __CLRCALL_PURE_OR_CDECL _Move_impl(void* const _Target, void* const _Source) noexcept {_Construct_in_place(*static_cast<_Ty*>(_Target), _STD move(*static_cast<_Ty*>(_Source)));}_Destroy_fn* _Destroy;_Copy_fn* _Copy;_Move_fn* _Move;
};
  • 先看big,先用using重定义了两个函数指针类型_Destroy_fn和_Copy_fn,现在写法都流行用using而不是typedef,不过本身using功能也更强大一些,这个结构体成员是这两个函数指针。再定义两个静态的模板函数,用来创建和释放内存,都是调用系统命名空间::下new与delete,不过new实际调用的是一个拷贝构造的函数。其都是重新申请和释放的内存,只是得到的结果是指针而已。
  • 再看small,结构基本等同big,只不过多了一个move的函数,支持移动语义。但仔细看它的三个静态成员函数,其并没有直接实现,而是利用了xutility文件中提供的标准模板函数_Construct_in_place与xmemory文件中的_Destroy_in_place标准模板函数。里面也没做什么,调用palcement new进构造函数调用与最后析构函数,也就是没有真正参与内存分配与释放,只是走了内存池那套流程,在已经分配好的内存上玩一圈。可以提供一下代码,其中_Construct_in_place还是可变模板参数的。
// FUNCTION TEMPLATE _Construct_in_place
template <class _Ty, class... _Types>
_CONSTEXPR20_DYNALLOC void _Construct_in_place(_Ty& _Obj, _Types&&... _Args) noexcept(is_nothrow_constructible_v<_Ty, _Types...>) {
#ifdef __cpp_lib_constexpr_dynamic_allocif (_STD is_constant_evaluated()) {_STD construct_at(_STD addressof(_Obj), _STD forward<_Types>(_Args)...);} else
#endif // __cpp_lib_constexpr_dynamic_alloc{::new (_Voidify_iter(_STD addressof(_Obj))) _Ty(_STD forward<_Types>(_Args)...);}
}template <class _Ty>
_CONSTEXPR20_DYNALLOC void _Destroy_in_place(_Ty& _Obj) noexcept {if constexpr (is_array_v<_Ty>) {_Destroy_range(_Obj, _Obj + extent_v<_Ty>);} else {_Obj.~_Ty();}
}

结构体中首先有对应的函数指针,另外,还提供了带模板的静态实现方法,实际用法是定义模板变量来保存 RTTI 结构体实例,实例中保存对应模板静态方法的指针,来为不同的类型提供 RTTI 功能:

template <class _Ty>
inline constexpr _Any_big_RTTI _Any_big_RTTI_obj = {&_Any_big_RTTI::_Destroy_impl<_Ty>, &_Any_big_RTTI::_Copy_impl<_Ty>};template <class _Ty>
inline constexpr _Any_small_RTTI _Any_small_RTTI_obj = {&_Any_small_RTTI::_Destroy_impl<_Ty>, &_Any_small_RTTI::_Copy_impl<_Ty>, &_Any_small_RTTI::_Move_impl<_Ty>};

4.std::any的构造函数

4.1.从std::any构造

    constexpr any() noexcept {}any(const any& _That) {_Storage._TypeData = _That._Storage._TypeData;switch (_Rep()) {case _Any_representation::_Small:_Storage._SmallStorage._RTTI = _That._Storage._SmallStorage._RTTI;_Storage._SmallStorage._RTTI->_Copy(&_Storage._SmallStorage._Data, &_That._Storage._SmallStorage._Data);break;case _Any_representation::_Big:_Storage._BigStorage._RTTI = _That._Storage._BigStorage._RTTI;_Storage._BigStorage._Ptr  = _Storage._BigStorage._RTTI->_Copy(_That._Storage._BigStorage._Ptr);break;case _Any_representation::_Trivial:default:_CSTD memcpy(_Storage._TrivialData, _That._Storage._TrivialData, sizeof(_Storage._TrivialData));break;}}any(any&& _That) noexcept {_Move_from(_That);}
  • 无参普通构造什么也没做
  • 拷贝构造先拷贝_TypeData,再处理_Storage的联合体,也就是处理对应的类型_Rep()直接返回类型,其原理也很简单,static_cast<_Any_representation>(_Storage._TypeData & _Rep_mask);,_Rep_mask前面提过是3,就这么轻松把类型提取出来了。再接着就是RTTI指针的拷贝,对于真正的数据,small型栈上move操作,并不真正分配内存,big型是真正new一下内存拷贝构造,trivial更是简单,只需要直接拷贝内存就可以了。
  • 移动语义拷贝构造,调用_Move_from,这个其实也简单,相比普通拷贝,small型调用move操作,big型拷贝内存指针,不重新申请内存,平凡性当然移动语义在这意义不大,直接还是内存拷贝。参见代码:
void _Move_from(any& _That) noexcept {_Storage._TypeData = _That._Storage._TypeData;switch (_Rep()) {case _Any_representation::_Small:_Storage._SmallStorage._RTTI = _That._Storage._SmallStorage._RTTI;_Storage._SmallStorage._RTTI->_Move(&_Storage._SmallStorage._Data, &_That._Storage._SmallStorage._Data);break;case _Any_representation::_Big:_Storage._BigStorage._RTTI = _That._Storage._BigStorage._RTTI;_Storage._BigStorage._Ptr  = _That._Storage._BigStorage._Ptr;_That._Storage._TypeData   = 0;break;case _Any_representation::_Trivial:default:_CSTD memcpy(_Storage._TrivialData, _That._Storage._TrivialData, sizeof(_Storage._TrivialData));break;}}

4.2.可变参数模板构造函数

template <class _ValueType, enable_if_t<conjunction_v<negation<is_same<decay_t<_ValueType>, any>>,is_copy_constructible<decay_t<_ValueType>>>,int> = 0>any& operator=(_ValueType&& _Value) {// replace contained value with an object of type decay_t<_ValueType> initialized from _Value*this = any{_STD forward<_ValueType>(_Value)};return *this;}// Modifiers [any.modifiers]template <class _ValueType, class... _Types,enable_if_t<conjunction_v<is_constructible<decay_t<_ValueType>, _Types...>, is_copy_constructible<decay_t<_ValueType>>>,int> = 0>decay_t<_ValueType>& emplace(_Types&&... _Args) {// replace contained value with an object of type decay_t<_ValueType> initialized from _Args...reset();return _Emplace<decay_t<_ValueType>>(_STD forward<_Types>(_Args)...);}template <class _ValueType, class _Elem, class... _Types,enable_if_t<conjunction_v<is_constructible<decay_t<_ValueType>, initializer_list<_Elem>&, _Types...>,is_copy_constructible<decay_t<_ValueType>>>,int> = 0>decay_t<_ValueType>& emplace(initializer_list<_Elem> _Ilist, _Types&&... _Args) {// replace contained value with an object of type decay_t<_ValueType> initialized from _Ilist and _Args...reset();return _Emplace<decay_t<_ValueType>>(_Ilist, _STD forward<_Types>(_Args)...);}
  • 一个参数的构造,enable_if_t在以前的文长说过了,主要为了借助SFINAE编译期判断,假设条件不通过,返回并没有定义type,否则返回int,并初始值为0,假如不能通过设为0为报错的,也就是匹配不成功,所有都失败,才会编译错误。就是能用一个参数进行构造,会走这里。
  • 可变参数的构造,结构基本同前面分析。注意一下,这个是explicit显式的函数,第一个参数传占位符,后面根构造用的参数。
  • 带初始化列表的构造,结构基本同前面分析。注意一下,这个是explicit显式的函数,第一个参数传占位符,第二个是初始化列表,后面跟具体的的参数。

三者的重点其实都落到了,_Emplace函数上了,我们看看具体实现

template <class _Decayed, class... _Types>_Decayed& _Emplace(_Types&&... _Args) { // emplace construct _Decayedif constexpr (_Any_is_trivial<_Decayed>) {// using the _Trivial representationauto& _Obj = reinterpret_cast<_Decayed&>(_Storage._TrivialData);_Construct_in_place(_Obj, _STD forward<_Types>(_Args)...);_Storage._TypeData =reinterpret_cast<uintptr_t>(&typeid(_Decayed)) | static_cast<uintptr_t>(_Any_representation::_Trivial);return _Obj;} else if constexpr (_Any_is_small<_Decayed>) {// using the _Small representationauto& _Obj = reinterpret_cast<_Decayed&>(_Storage._SmallStorage._Data);_Construct_in_place(_Obj, _STD forward<_Types>(_Args)...);_Storage._SmallStorage._RTTI = &_Any_small_RTTI_obj<_Decayed>;_Storage._TypeData =reinterpret_cast<uintptr_t>(&typeid(_Decayed)) | static_cast<uintptr_t>(_Any_representation::_Small);return _Obj;} else {// using the _Big representation_Decayed* const _Ptr       = ::new _Decayed(_STD forward<_Types>(_Args)...);_Storage._BigStorage._Ptr  = _Ptr;_Storage._BigStorage._RTTI = &_Any_big_RTTI_obj<_Decayed>;_Storage._TypeData =reinterpret_cast<uintptr_t>(&typeid(_Decayed)) | static_cast<uintptr_t>(_Any_representation::_Big);return *_Ptr;}}

可以看出_Emplace是any与真正的类型转换实现,这个模板第一个参数作了返回值,是无法推断的,必显示的传入,我们也看到都是显示传入T的退化类型的。有了前部分的分析,也是非常的容易了,先判断是trivial还是small还是big类型,方法已经说过。

  • trivial:这种来说,真接内存强转,然后_Construct_in_place实质是STL的方法,就是调用placement new进行构造的,再设置_TypeData,这些都是容易处理的。
  • small这里和trivial没有本质上的区别,只是内存变成48字节内了,然后多了一个RTTI指针获取,构造函数也真正起作用,不像tirival
  • big类型更是容易,直接new内存进行显示的T(args...)构造,模板参数包展开,他们都是万能引用与完美转发,然后将申请并初始化的内存地址交给了_Storage._BigStorage._Ptr

总结:small型与trivial型都是没有直接进行堆内存再申请,,在any已经有的64个字节内强转操作,不同的small会真正处理调用构造函数,big型来说是进行再次堆内存申请,然后存其指针。

4.3.赋值构造与emplace函数

这个没什么好说的,实际还是调用前面说的拷贝构造与带参的构造,包装过一层而已。

// Assignment [any.assign]any& operator=(const any& _That) {*this = any{_That};return *this;}any& operator=(any&& _That) noexcept {reset();_Move_from(_That);return *this;}template <class _ValueType, enable_if_t<conjunction_v<negation<is_same<decay_t<_ValueType>, any>>,is_copy_constructible<decay_t<_ValueType>>>,int> = 0>any& operator=(_ValueType&& _Value) {// replace contained value with an object of type decay_t<_ValueType> initialized from _Value*this = any{_STD forward<_ValueType>(_Value)};return *this;}// Modifiers [any.modifiers]template <class _ValueType, class... _Types,enable_if_t<conjunction_v<is_constructible<decay_t<_ValueType>, _Types...>, is_copy_constructible<decay_t<_ValueType>>>,int> = 0>decay_t<_ValueType>& emplace(_Types&&... _Args) {// replace contained value with an object of type decay_t<_ValueType> initialized from _Args...reset();return _Emplace<decay_t<_ValueType>>(_STD forward<_Types>(_Args)...);}template <class _ValueType, class _Elem, class... _Types,enable_if_t<conjunction_v<is_constructible<decay_t<_ValueType>, initializer_list<_Elem>&, _Types...>,is_copy_constructible<decay_t<_ValueType>>>,int> = 0>decay_t<_ValueType>& emplace(initializer_list<_Elem> _Ilist, _Types&&... _Args) {// replace contained value with an object of type decay_t<_ValueType> initialized from _Ilist and _Args...reset();return _Emplace<decay_t<_ValueType>>(_Ilist, _STD forward<_Types>(_Args)...);}

从中可以看出,operator=、emplace内部都是调用的_Emplace。

5.reset函数

void reset() noexcept { // transition to the empty stateswitch (_Rep()) {case _Any_representation::_Small:_Storage._SmallStorage._RTTI->_Destroy(&_Storage._SmallStorage._Data);break;case _Any_representation::_Big:_Storage._BigStorage._RTTI->_Destroy(_Storage._BigStorage._Ptr);break;case _Any_representation::_Trivial:default:break;}_Storage._TypeData = 0;}

        reset就是调用析构和释放内存的,对于small来说,不用释放内存,内部直接调用析构,对于big来说,其实际是delete,即析构还释放内存,对trivial来说,不用处理内存相关,最后都将_TypeData清零。

6._Cast函数

template <class _Decayed>_NODISCARD const _Decayed* _Cast() const noexcept {// if *this contains a value of type _Decayed, return a pointer to itconst type_info* const _Info = _TypeInfo();if (!_Info || *_Info != typeid(_Decayed)) {return nullptr;}if constexpr (_Any_is_trivial<_Decayed>) {// get a pointer to the contained _Trivial value of type _Decayedreturn reinterpret_cast<const _Decayed*>(&_Storage._TrivialData);} else if constexpr (_Any_is_small<_Decayed>) {// get a pointer to the contained _Small value of type _Decayedreturn reinterpret_cast<const _Decayed*>(&_Storage._SmallStorage._Data);} else {// get a pointer to the contained _Big value of type _Decayedreturn static_cast<const _Decayed*>(_Storage._BigStorage._Ptr);}}template <class _Decayed>_NODISCARD _Decayed* _Cast() noexcept { // if *this contains a value of type _Decayed, return a pointer to itreturn const_cast<_Decayed*>(static_cast<const any*>(this)->_Cast<_Decayed>());}

_Cast是类型转换,提供const与非const两个版本,也是内存地址强转,big用的_Storage._BigStorage._Ptr,samll用&_Storage._SmallStorage._Data,当然trivial用的是&_Storage._TrivialData。

7.make_any模版函数

template <class _ValueType, class... _Types>
_NODISCARD any make_any(_Types&&... _Args) { // construct an any containing a _ValueType initialized with _Args...return any{in_place_type<_ValueType>, _STD forward<_Types>(_Args)...};
}
template <class _ValueType, class _Elem, class... _Types>
_NODISCARD any make_any(initializer_list<_Elem> _Ilist, _Types&&... _Args) {// construct an any containing a _ValueType initialized with _Ilist and _Args...return any{in_place_type<_ValueType>, _Ilist, _STD forward<_Types>(_Args)...};
}

就是将参数透传到 std::any 的初始化列表构造并执行。

8.std::any_cast函数

template <class _ValueType>
_NODISCARD const _ValueType* any_cast(const any* const _Any) noexcept {// retrieve a pointer to the _ValueType contained in _Any, or nullstatic_assert(!is_void_v<_ValueType>, "std::any cannot contain void.");if constexpr (is_function_v<_ValueType> || is_array_v<_ValueType>) {return nullptr;} else {if (!_Any) {return nullptr;}return _Any->_Cast<_Remove_cvref_t<_ValueType>>();}
}
template <class _ValueType>
_NODISCARD _ValueType* any_cast(any* const _Any) noexcept {// retrieve a pointer to the _ValueType contained in _Any, or nullstatic_assert(!is_void_v<_ValueType>, "std::any cannot contain void.");if constexpr (is_function_v<_ValueType> || is_array_v<_ValueType>) {return nullptr;} else {if (!_Any) {return nullptr;}return _Any->_Cast<_Remove_cvref_t<_ValueType>>();}
}template <class _Ty>
_NODISCARD remove_cv_t<_Ty> any_cast(const any& _Any) {static_assert(is_constructible_v<remove_cv_t<_Ty>, const _Remove_cvref_t<_Ty>&>,"any_cast<T>(const any&) requires remove_cv_t<T> to be constructible from ""const remove_cv_t<remove_reference_t<T>>&");const auto _Ptr = _STD any_cast<_Remove_cvref_t<_Ty>>(&_Any);if (!_Ptr) {_Throw_bad_any_cast();}return static_cast<remove_cv_t<_Ty>>(*_Ptr);
}
template <class _Ty>
_NODISCARD remove_cv_t<_Ty> any_cast(any& _Any) {static_assert(is_constructible_v<remove_cv_t<_Ty>, _Remove_cvref_t<_Ty>&>,"any_cast<T>(any&) requires remove_cv_t<T> to be constructible from remove_cv_t<remove_reference_t<T>>&");const auto _Ptr = _STD any_cast<_Remove_cvref_t<_Ty>>(&_Any);if (!_Ptr) {_Throw_bad_any_cast();}return static_cast<remove_cv_t<_Ty>>(*_Ptr);
}
template <class _Ty>
_NODISCARD remove_cv_t<_Ty> any_cast(any&& _Any) {static_assert(is_constructible_v<remove_cv_t<_Ty>, _Remove_cvref_t<_Ty>>,"any_cast<T>(any&&) requires remove_cv_t<T> to be constructible from remove_cv_t<remove_reference_t<T>>");const auto _Ptr = _STD any_cast<_Remove_cvref_t<_Ty>>(&_Any);if (!_Ptr) {_Throw_bad_any_cast();}return static_cast<remove_cv_t<_Ty>>(_STD move(*_Ptr));
}

所有 std::any_cast 最终都会先取保存的 std::type_info 然后与目标类型相比较,失败则抛出 std::bad_any_cast,否则则返回 value。这里要注意的是返回的类型会根据 std::any_cast 的入参产生变化:

  • const any* const -> const _ValueType*
  • any* const _Any -> _ValueType*
  • const any& _Any -> remove_cv_t<_Ty>
  • any& _Any -> remove_cv_t<_Ty>
  • any&& _Any -> remove_cv_t<_Ty>

总结起来就是入参的 std::any 为指针时,返回指针,否则返回 remove_cv_t<_Ty>,所以使用时如果对应的是结构体 / 类,应该尽量获取指针或者引用来保持高效,避免内存拷贝降低性能(例子可以看前面的介绍)。

9.总结

        到此我们已经全部分析完毕,任何做技术的都是要知其然,更好知其所以然。只要这样,才能把这些设计手法运用到我们平时的项目当中,只有你能熟练的运用了才是真正的掌握了。还是那句话,纸上得来终觉浅,绝知此事要躬行。

相关推荐阅读

std::is_trivially_copyable

std::is_move_constructible

C++内存分配策略

这篇关于C++三剑客之std::any(二) : 源码剖析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/997683

相关文章

关于C++中的虚拟继承的一些总结(虚拟继承,覆盖,派生,隐藏)

1.为什么要引入虚拟继承 虚拟继承是多重继承中特有的概念。虚拟基类是为解决多重继承而出现的。如:类D继承自类B1、B2,而类B1、B2都继承自类A,因此在类D中两次出现类A中的变量和函数。为了节省内存空间,可以将B1、B2对A的继承定义为虚拟继承,而A就成了虚拟基类。实现的代码如下: class A class B1:public virtual A; class B2:pu

C++对象布局及多态实现探索之内存布局(整理的很多链接)

本文通过观察对象的内存布局,跟踪函数调用的汇编代码。分析了C++对象内存的布局情况,虚函数的执行方式,以及虚继承,等等 文章链接:http://dev.yesky.com/254/2191254.shtml      论C/C++函数间动态内存的传递 (2005-07-30)   当你涉及到C/C++的核心编程的时候,你会无止境地与内存管理打交道。 文章链接:http://dev.yesky

C++的模板(八):子系统

平常所见的大部分模板代码,模板所传的参数类型,到了模板里面,或实例化为对象,或嵌入模板内部结构中,或在模板内又派生了子类。不管怎样,最终他们在模板内,直接或间接,都实例化成对象了。 但这不是唯一的用法。试想一下。如果在模板内限制调用参数类型的构造函数会发生什么?参数类的对象在模板内无法构造。他们只能从模板的成员函数传入。模板不保存这些对象或者只保存他们的指针。因为构造函数被分离,这些指针在模板外

C++工程编译链接错误汇总VisualStudio

目录 一些小的知识点 make工具 可以使用windows下的事件查看器崩溃的地方 dumpbin工具查看dll是32位还是64位的 _MSC_VER .cc 和.cpp 【VC++目录中的包含目录】 vs 【C/C++常规中的附加包含目录】——头文件所在目录如何怎么添加,添加了以后搜索头文件就会到这些个路径下搜索了 include<> 和 include"" WinMain 和

C/C++的编译和链接过程

目录 从源文件生成可执行文件(书中第2章) 1.Preprocessing预处理——预处理器cpp 2.Compilation编译——编译器cll ps:vs中优化选项设置 3.Assembly汇编——汇编器as ps:vs中汇编输出文件设置 4.Linking链接——链接器ld 符号 模块,库 链接过程——链接器 链接过程 1.简单链接的例子 2.链接过程 3.地址和

C++必修:模版的入门到实践

✨✨ 欢迎大家来到贝蒂大讲堂✨✨ 🎈🎈养成好习惯,先赞后看哦~🎈🎈 所属专栏:C++学习 贝蒂的主页:Betty’s blog 1. 泛型编程 首先让我们来思考一个问题,如何实现一个交换函数? void swap(int& x, int& y){int tmp = x;x = y;y = tmp;} 相信大家很快就能写出上面这段代码,但是如果要求这个交换函数支持字符型

C++入门01

1、.h和.cpp 源文件 (.cpp)源文件是C++程序的实际实现代码文件,其中包含了具体的函数和类的定义、实现以及其他相关的代码。主要特点如下:实现代码: 源文件中包含了函数、类的具体实现代码,用于实现程序的功能。编译单元: 源文件通常是一个编译单元,即单独编译的基本单位。每个源文件都会经过编译器的处理,生成对应的目标文件。包含头文件: 源文件可以通过#include指令引入头文件,以使

springboot家政服务管理平台 LW +PPT+源码+讲解

3系统的可行性研究及需求分析 3.1可行性研究 3.1.1技术可行性分析 经过大学四年的学习,已经掌握了JAVA、Mysql数据库等方面的编程技巧和方法,对于这些技术该有的软硬件配置也是齐全的,能够满足开发的需要。 本家政服务管理平台采用的是Mysql作为数据库,可以绝对地保证用户数据的安全;可以与Mysql数据库进行无缝连接。 所以,家政服务管理平台在技术上是可以实施的。 3.1

C++面试八股文:std::deque用过吗?

100编程书屋_孔夫子旧书网 某日二师兄参加XXX科技公司的C++工程师开发岗位第26面: 面试官:deque用过吗? 二师兄:说实话,很少用,基本没用过。 面试官:为什么? 二师兄:因为使用它的场景很少,大部分需要性能、且需要自动扩容的时候使用vector,需要随机插入和删除的时候可以使用list。 面试官:那你知道STL中的stack是如何实现的吗? 二师兄:默认情况下,stack使

高仿精仿愤怒的小鸟android版游戏源码

这是一款很完美的高仿精仿愤怒的小鸟android版游戏源码,大家可以研究一下吧、 为了报复偷走鸟蛋的肥猪们,鸟儿以自己的身体为武器,仿佛炮弹一样去攻击肥猪们的堡垒。游戏是十分卡通的2D画面,看着愤怒的红色小鸟,奋不顾身的往绿色的肥猪的堡垒砸去,那种奇妙的感觉还真是令人感到很欢乐。而游戏的配乐同样充满了欢乐的感觉,轻松的节奏,欢快的风格。 源码下载