gpt4 book ai didi

c++ - std::allocator::max_size() 背后的基本原理是什么?

转载 作者:太空狗 更新时间:2023-10-29 20:41:13 26 4
gpt4 key购买 nike

我知道 std::allocator 中的 max_size() 是理论上的限制,但我只是尝试了一些东西,我得到的数字非常大;那么我应该如何解释这个数字以及这个函数背后的哲学是什么?

我的例子:

#include <iostream>
#include <memory>
#include <cstdint>
typedef int8_t Tnum_1;
struct X
{
template <typename T>
static void printAllocInfo()
{
std::cout << std::allocator<T>().max_size() << "\t Alloc max_size\n";
std::cout << ((std::allocator<T>().max_size()) / (1024))
<< "\t Alloc max_size / 1024\n";
std::cout << (((std::allocator<T>().max_size()) / (1024)) / (1024))
<< "\t\t Alloc max_size / 1024 / 1024\n";
}
};
int main()
{
X::printAllocInfo<Tnum_1>();
return (0);
}

它打印:

18446744073709551615     Alloc max_size
18014398509481983 Alloc max_size / 1024
17592186044415 Alloc max_size / 1024 / 1024

考虑到我刚刚使用 int8_t 作为模板参数,这意味着我可以在我的机器上分配 18446744073709551615 字节?这个数字太大了,以至于开始失去任何实际意义。

最佳答案

您引用的数字当然是 2^64 -1,也就是可以表示的最大 64 位无符号整数。所有 max_size() 表示它不支持任何更大的东西,而不是它支持小于该尺寸的所有东西。

这取决于您的操作系统是否实际将其提供给您的程序。但是,由于您可以在运行它的不同机器(包括遥远 future 的机器)上编译程序,因此没有理由将 max_size() 限制为较小的数字。

注意:如果您阅读 C++ 标准中的表 31 — 分配器要求,您会发现以下类型的分配器对象 a X:

a.allocate(n): Memory is allocated for n objects of type T but objects are not constructed.

a.max_size(): the largest value that can meaningfully be passed to X::allocate()

所以 max_size 是可以分配的最大对象数,而不是字节数。

关于c++ - std::allocator::max_size() 背后的基本原理是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22183162/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com