c++11 function源码分析

c++11 function源码分析以 VS2019 function 源码为例分析 class function template lt class Fty gt class function public Get function impl lt Fty gt type wrapper for callable objects private

大家好,我是讯享网,很高兴认识大家。

以VS2019 function源码为例分析。

class function:

template <class _Fty> class function : public _Get_function_impl<_Fty>::type { 
    // wrapper for callable objects private: using _Mybase = typename _Get_function_impl<_Fty>::type; public: function() noexcept { 
    // construct empty function wrapper } function(nullptr_t) noexcept { 
    // construct empty function wrapper from null pointer } function(const function& _Right) { 
    // construct holding copy of _Right this->_Reset_copy(_Right); } template <class _Fx, class = typename _Mybase::template _Enable_if_callable_t<_Fx&, function>> function(_Fx _Func) { 
    // construct wrapper holding copy of _Func this->_Reset(_STD move(_Func)); } ... }; 

讯享网

class function继承自public _Get_function_impl<_Fty>::type

讯享网 template <class _Ret, class... _Types> \ struct _Get_function_impl<_Ret CALL_OPT(_Types...)> { 
    /* determine type from argument list */ \ using type = _Func_class<_Ret, _Types...>; \ }; 

class _Func_class:

template <class _Ret, class... _Types> class _Func_class : public _Arg_types<_Types...> { 
    // implement function template public: using result_type = _Ret; using _Ptrt = _Func_base<_Ret, _Types...>; _Func_class() noexcept { 
    // construct without stored object _Set(nullptr); } _Ret operator()(_Types... _Args) const { 
    // call through stored object if (_Empty()) { 
    _Xbad_function_call(); } const auto _Impl = _Getimpl(); return _Impl->_Do_call(_STD forward<_Types>(_Args)...); } ~_Func_class() noexcept { 
    // destroy the object _Tidy(); } protected: template <class _Fx> void _Reset(_Fx&& _Val) { 
    // store copy of _Val if (!_Test_callable(_Val)) { 
    // null member pointer/function pointer/std::function return; // already empty } using _Impl = _Func_impl_no_alloc<decay_t<_Fx>, _Ret, _Types...>; _Reset_impl<_Impl>(_STD forward<_Fx>(_Val), _Is_large<_Impl>{ 
   }); } template <class _Myimpl, class _Fx> void _Reset_impl(_Fx&& _Val, true_type) { 
    // store copy of _Val, large (dynamically allocated) _Set(_Global_new<_Myimpl>(_STD forward<_Fx>(_Val))); } template <class _Myimpl, class _Fx> void _Reset_impl(_Fx&& _Val, false_type) { 
    // store copy of _Val, small (locally stored) _Set(::new (_Getspace()) _Myimpl(_STD forward<_Fx>(_Val))); } private: union _Storage { 
    // storage for small objects (basic_string is small) max_align_t _Dummy1; // for maximum alignment char _Dummy2[_Space_size]; // to permit aliasing _Ptrt* _Ptrs[_Small_object_num_ptrs]; // _Ptrs[_Small_object_num_ptrs - 1] is reserved }; _Storage _Mystorage; enum { 
    _EEN_IMPL = _Small_object_num_ptrs - 1 }; // helper for expression evaluator _Ptrt* _Getimpl() const noexcept { 
    // get pointer to object return _Mystorage._Ptrs[_Small_object_num_ptrs - 1]; } void _Set(_Ptrt* _Ptr) noexcept { 
    // store pointer to object _Mystorage._Ptrs[_Small_object_num_ptrs - 1] = _Ptr; } void* _Getspace() noexcept { 
    // get pointer to storage space return &_Mystorage; } const void* _Getspace() const noexcept { 
    // get pointer to storage space return &_Mystorage; } }; 

class _Func_impl_no_alloc

讯享网template <class _Callable, class _Rx, class... _Types> class _Func_impl_no_alloc final : public _Func_base<_Rx, _Types...> { 
    // derived class for specific implementation types that don't use allocators public: using _Mybase = _Func_base<_Rx, _Types...>; using _Nothrow_move = is_nothrow_move_constructible<_Callable>; template <class _Other, class = enable_if_t<!is_same_v<_Func_impl_no_alloc, decay_t<_Other>>>> explicit _Func_impl_no_alloc(_Other&& _Val) : _Callee(_STD forward<_Other>(_Val)) { 
    // construct } // dtor non-virtual due to _Delete_this() private: virtual _Mybase* _Copy(void* _Where) const override { 
    // return clone of *this return _Clone(_Where, _Is_large<_Func_impl_no_alloc>{ 
   }); } _Mybase* _Clone(void*, true_type) const { 
    // return clone of *this, large (dynamically allocated) return _Global_new<_Func_impl_no_alloc>(_Callee); } _Mybase* _Clone(void* _Where, false_type) const { 
    // return clone of *this, small (locally stored) return ::new (_Where) _Func_impl_no_alloc(_Callee); } virtual _Mybase* _Move(void* _Where) override { 
    // return clone of *this return ::new (_Where) _Func_impl_no_alloc(_STD move(_Callee)); } virtual _Rx _Do_call(_Types&&... _Args) override { 
    // call wrapped function return _Invoker_ret<_Rx>::_Call(_Callee, _STD forward<_Types>(_Args)...); } _Callable _Callee; }; 

我们从template <class _Fx, class = typename _Mybase::template _Enable_if_callable_t<_Fx&, function>> function(_Fx _Func)这个构造函数入手。调用到基类_Func_class的template void _Reset(_Fx&& _Val)函数。这个函数中关键下面两句代码:

using _Impl = _Func_impl_no_alloc<decay_t<_Fx>, _Ret, _Types...>; _Reset_impl<_Impl>(_STD forward<_Fx>(_Val), _Is_large<_Impl>{ 
   }); 

_Is_large的定义:

讯享网constexpr int _Small_object_num_ptrs = 6 + 16 / sizeof(void*); constexpr size_t _Space_size = (_Small_object_num_ptrs - 1) * sizeof(void*); template <class _Impl> // determine whether _Impl must be dynamically allocated using _Is_large = bool_constant<(_Space_size < sizeof(_Impl)) || !_Impl::_Nothrow_move::value>; 

如果_Impl类的size大于_Space_size则为true,否则为false。如果是64位系统,不难算出_Small_object_num_ptrs的大小为8, _Space_size的大小则为78=56,也就是7个指针大小。
再看类中成员变量_Mystorage的定义:
union _Storage { // storage for small objects (basic_string is small)
max_align_t _Dummy1; // for maximum alignment
char _Dummy2[_Space_size]; // to permit aliasing
_Ptrt
_Ptrs[_Small_object_num_ptrs]; // _Ptrs[_Small_object_num_ptrs - 1] is reserved
};
_Ptrs为8个指针大小空间的指针数组。_Dummy2为7个指针大小空间的char数组。

所以,如果_Impl类的size小于等于7个指针大小,调用

 template <class _Myimpl, class _Fx> void _Reset_impl(_Fx&& _Val, false_type) { 
    // store copy of _Val, small (locally stored) _Set(::new (_Getspace()) _Myimpl(_STD forward<_Fx>(_Val))); } 

这里用到了placement new,将_Myimpl对象放到成员变量_Mystorage指向空间的前56个字节,也即_Dummy2。然后调用_Set函数将_Myimpl对象指针赋值给数组_Ptrs的最后一个元素_Ptrs[_Small_object_num_ptrs - 1]。


讯享网

如果_Impl类的size大于7个指针大小,调用

讯享网 template <class _Myimpl, class _Fx> void _Reset_impl(_Fx&& _Val, true_type) { 
    // store copy of _Val, large (dynamically allocated) _Set(_Global_new<_Myimpl>(_STD forward<_Fx>(_Val))); } 

new出一个_Myimpl对象,然后调用_Set函数将_Myimpl对象指针赋值给数组_Ptrs的最后一个元素_Ptrs[_Small_object_num_ptrs - 1]。

这时传入的函数对象保存在_Myimpl对象中,也即数组_Ptrs的最后一个元素_Ptrs[_Small_object_num_ptrs - 1]指向的地址。

从function的使用经验可知,一个function构造完成,调用的时候是operator()。这个operator()运算符重载函数在基类_Func_class中实现的。

const auto _Impl = _Getimpl(); return _Impl->_Do_call(_STD forward<_Types>(_Args)...); 

_Getimpl函数其实是取得之前保存的_Myimpl对象指针。然后调用class _Func_impl_no_alloc的_Do_call函数。

讯享网_Invoker_ret<_Rx>::_Call(_Callee, _STD forward<_Types>(_Args)...); 

_Callee为之前保存的函数指针,_Args…为调用function是传入的可变参数。

_Invoker_ret是一个结构体,_Call是它的static成员函数。

// 泛化版本 template <class _Rx, bool = is_void_v<_Rx>> struct _Invoker_ret { 
   }; // helper to give INVOKE an explicit return type; avoids undesirable Expression SFINAE struct _Unforced { 
   }; // tag to distinguish bind() from bind<R>() // 返回值为void的特化版本(部分具体化) template <class _Cv_void> struct _Invoker_ret<_Cv_void, true> { 
    // selected for _Rx being cv void template <class... _Valtys> static void _Call(_Valtys&&... _Vals) { 
    // INVOKE, "implicitly" converted to void _STD invoke(_STD forward<_Valtys>(_Vals)...); } }; // 返回值为非void的特化版本(部分具体化) template <class _Rx> struct _Invoker_ret<_Rx, false> { 
    // selected for all _Rx other than cv void and _Unforced template <class... _Valtys> static _Rx _Call(_Valtys&&... _Vals) { 
    // INVOKE, implicitly converted to _Rx return _STD invoke(_STD forward<_Valtys>(_Vals)...); } }; // 特化版本,function这里不会调用到,bind中会用到,_Unforced只是一个tag的作用。 template <> struct _Invoker_ret<_Unforced, false> { 
    // selected for _Rx being _Unforced template <class... _Valtys> static auto _Call(_Valtys&&... _Vals) -> decltype(_STD invoke(_STD forward<_Valtys>(_Vals)...)) { 
    // INVOKE, unchanged return _STD invoke(_STD forward<_Valtys>(_Vals)...); } }; 

看源码比较容易理解。最终通过invoke调用。

invoke具体实现:

讯享网#define _IMPLEMENT_INVOKE(NAME_PREFIX, CONSTEXPR) \ /* FUNCTION TEMPLATE invoke */ // 一个对象的成员函数 \ struct _CONCAT(NAME_PREFIX, _Invoker_pmf_object) { 
    /* INVOKE a pointer to member function on an object */ \ template <class _Decayed, class _Ty1, class... _Types2> \ static CONSTEXPR auto _Call(_Decayed _Pmf, _Ty1&& _Arg1, _Types2&&... _Args2) \ _NOEXCEPT_COND(noexcept((_STD forward<_Ty1>(_Arg1).*_Pmf)(_STD forward<_Types2>(_Args2)...))) \ -> decltype((_STD forward<_Ty1>(_Arg1).*_Pmf)( \ _STD forward<_Types2>(_Args2)...)) { 
    /* INVOKE a pointer to member function on an object */ \ return (_STD forward<_Ty1>(_Arg1).*_Pmf)(_STD forward<_Types2>(_Args2)...); \ } \ }; \ // reference_wrapper对象的成员函数 \ struct _CONCAT( \ NAME_PREFIX, _Invoker_pmf_refwrap) { 
    /* INVOKE a pointer to member function on a reference_wrapper */ \ template <class _Decayed, class _Ty1, class... _Types2> \ static CONSTEXPR auto _Call(_Decayed _Pmf, _Ty1&& _Arg1, _Types2&&... _Args2) \ _NOEXCEPT_COND(noexcept((_STD forward<_Ty1>(_Arg1).get().*_Pmf)(_STD forward<_Types2>(_Args2)...))) \ -> decltype((_STD forward<_Ty1>(_Arg1).get().*_Pmf)(_STD forward<_Types2>( \ _Args2)...)) { 
    /* INVOKE a pointer to member function on a reference_wrapper */ \ return (_STD forward<_Ty1>(_Arg1).get().*_Pmf)(_STD forward<_Types2>(_Args2)...); \ } \ }; \ // 一个智能指针或者普通指针指向对象的成员函数 \ struct _CONCAT(NAME_PREFIX, _Invoker_pmf_pointer) { 
    /* INVOKE a pointer to member function on a [smart] pointer */ \ template <class _Decayed, class _Ty1, class... _Types2> \ static CONSTEXPR auto _Call(_Decayed _Pmf, _Ty1&& _Arg1, _Types2&&... _Args2) \ _NOEXCEPT_COND(noexcept(((*_STD forward<_Ty1>(_Arg1)).*_Pmf)(_STD forward<_Types2>(_Args2)...))) \ -> decltype(((*_STD forward<_Ty1>(_Arg1)).*_Pmf)(_STD forward<_Types2>( \ _Args2)...)) { 
    /* INVOKE a pointer to member function on a [smart] pointer */ \ return ((*_STD forward<_Ty1>(_Arg1)).*_Pmf)(_STD forward<_Types2>(_Args2)...); \ } \ }; \ // 一个对象的成员变量 \ struct _CONCAT(NAME_PREFIX, _Invoker_pmd_object) { 
    /* INVOKE a pointer to member data on an object */ \ template <class _Decayed, class _Ty1> \ static CONSTEXPR auto _Call(_Decayed _Pmd, _Ty1&& _Arg1) \ _NOEXCEPT_COND(noexcept(_STD forward<_Ty1>(_Arg1).*_Pmd)) \ -> decltype(_STD forward<_Ty1>(_Arg1).*_Pmd) { 
    /* INVOKE a pointer to member data on an object */ \ return _STD forward<_Ty1>(_Arg1).*_Pmd; \ } \ }; \ // reference_wrapper对象的成员变量 \ struct _CONCAT(NAME_PREFIX, _Invoker_pmd_refwrap) { 
    /* INVOKE a pointer to member data on a reference_wrapper */ \ template <class _Decayed, class _Ty1> \ static CONSTEXPR auto _Call(_Decayed _Pmd, _Ty1&& _Arg1) \ _NOEXCEPT_COND(noexcept(_STD forward<_Ty1>(_Arg1).get().*_Pmd)) -> decltype( \ _STD forward<_Ty1>(_Arg1).get().*_Pmd) { 
    /* INVOKE a pointer to member data on a reference_wrapper */ \ return _STD forward<_Ty1>(_Arg1).get().*_Pmd; \ } \ }; \ // 一个智能指针或者普通指针指向对象的成员变量 \ struct _CONCAT(NAME_PREFIX, _Invoker_pmd_pointer) { 
    /* INVOKE a pointer to member data on a [smart] pointer */ \ template <class _Decayed, class _Ty1> \ static CONSTEXPR auto _Call(_Decayed _Pmd, _Ty1&& _Arg1) \ _NOEXCEPT_COND(noexcept((*_STD forward<_Ty1>(_Arg1)).*_Pmd)) -> decltype( \ (*_STD forward<_Ty1>(_Arg1)).*_Pmd) { 
    /* INVOKE a pointer to member data on a [smart] pointer */ \ return (*_STD forward<_Ty1>(_Arg1)).*_Pmd; \ } \ }; \ // 一个普通函数或者一个对象的operator() \ struct _CONCAT(NAME_PREFIX, _Invoker_functor) { 
    /* INVOKE a function object */ \ template <class _Callable, class... _Types> \ static CONSTEXPR auto _Call(_Callable&& _Obj, _Types&&... _Args) \ _NOEXCEPT_COND(noexcept(_STD forward<_Callable>(_Obj)(_STD forward<_Types>(_Args)...))) -> decltype( \ _STD forward<_Callable>(_Obj)(_STD forward<_Types>(_Args)...)) { 
    /* INVOKE a function object */ \ return _STD forward<_Callable>(_Obj)(_STD forward<_Types>(_Args)...); \ } \ }; \ \ ... _IMPLEMENT_INVOKE(_EMPTY_ARGUMENT, inline) 

从invoke的实现代码可以看出,它列举出了针对各种function可支持的函数形式(callable object)。
1. 普通C函数
2. 实现了operator()的类或结构体对象
3. 对象(对象引用,对象指针,对象智能指针,对象引用包装)的成员变量或者成员函数
4. lambda表达式
5. bind包裹的对象(_Binder对象)
6. 以及上述类型的模板类型

小讯
上一篇 2025-04-09 11:44
下一篇 2025-02-11 08:13

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/131900.html