C++ std::unique_ptr : Why isn't there any size fees with lambdas?

后端 未结 4 2078
暖寄归人
暖寄归人 2020-12-28 12:03

I am reading \"Effective Modern C++\". In the item related to std::unique_ptr it\'s stated that if the custom deleter is a stateless object, then no size fees o

4条回答
  •  佛祖请我去吃肉
    2020-12-28 12:52

    A unique_ptr must always store its deleter. Now, if the deleter is a class type with no state, then the unique_ptr can make use of empty base optimization so that the deleter does not use any additional space.

    How exactly this is done differs between implementations. For instance, both libc++ and MSVC store the managed pointer and the deleter in a compressed pair, which automatically gets you empty base optimization if one of the types involved is an empty class.

    From the libc++ link above

    template  >
    class _LIBCPP_TYPE_VIS_ONLY unique_ptr
    {
    public:
        typedef _Tp element_type;
        typedef _Dp deleter_type;
        typedef typename __pointer_type<_Tp, deleter_type>::type pointer;
    private:
        __compressed_pair __ptr_;
    

    libstdc++ stores the two in an std::tuple and some Google searching suggests their tuple implementation employs empty base optimization but I can't find any documentation stating so explicitly.

    In any case, this example demonstrates that both libc++ and libstdc++ use EBO to reduce the size of a unique_ptr with an empty deleter.

提交回复
热议问题