首页 > 解决方案 > 与 STL 和 std::basic_string 不同,为什么 std::function 没有默认分配器

问题描述

与 STL 和 不同std::basic_string,没有默认分配器std::function。为什么?

C++11中没有默认分配器std::function。但是这篇文章(https://docs.microsoft.com/en-us/cpp/standard-library/allocators?view=msvc-160)持有相反的观点,它说:

在 C++11 中,所有采用分配器类型参数的标准库类型和函数都支持最小分配器接口,包括std::functionshared_ptrallocate_shared()basic_string.

template< class Alloc >
function( std::allocator_arg_t, const Alloc& alloc,
              std::nullptr_t ) noexcept;

template<
    class CharT,
    class Traits = std::char_traits<CharT>,
    class Allocator = std::allocator<CharT>
> class basic_string;

template<class T,
class Allocator = std::allocator<T>
> class vector;

标签: c++c++11stlstd-functionallocator

解决方案


在 C++11 及更高版本中,最常用的非默认构造函数是这个:

template<class F> function(F);

我将忽略其他讨论,因为它们不太有趣,但相同的信息适用于它们。

在 C++11 和 C++14 中它也有这个,它在 C++20 中被删除:

template<class F, class Alloc> function(std::allocator_arg_t, const Alloc&, F);

你的问题是为什么它在 C++11 和 C++14 中没有这个而不是上面的构造函数:

template<class F, class Alloc> function(F, const Alloc& = Alloc());

答案是没有办法使用默认参数调用这样的构造函数,因为function(f)总是调用第一个构造函数,而 C++ 没有办法指定Alloc模板参数。有关 C++ 限制的更多信息,请参见此处:可以显式指定构造函数的模板参数吗?

许多其他类型(如 std::vector)是不同的,因为它们的分配器模板参数在整个类类型上,而不仅仅是在其构造函数上。


推荐阅读