c++ - 与 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::function
、shared_ptr
、allocate_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++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)是不同的,因为它们的分配器模板参数在整个类类型上,而不仅仅是在其构造函数上。
推荐阅读
- active-directory - 在未建立信任的情况下,在两个林中的一个控制台中管理 GPO
- kotlin - 更改 Exposed ORM 中的 ID 名称
- azure - Azure IOT HUB,更改 MQTT 版本?
- typescript - 使用单元组防止带有条件的分布条件类型时不合理和未检测到的循环类型定义
- python - 如何为 Jupyter 笔记本中的新结构扩展 SymPy 漂亮打印?
- javascript - 文件导出 HTTP 端点 GET 与 POST
- sql-server - system_user 是否在 SQL 语句中多次运行?
- azure - 从 MCAS 策略中检索治理操作
- amazon-web-services - 我如何知道谁在向我的 Amazon API Gateway 终端节点发出请求?
- python - Python量子傅里叶变换