malloc 和 std::allocator<T>::allocate 的区别
Difference between malloc and std::allocator<T>::allocate
我知道这两个函数都接受 size_t
数字。对于 malloc
,该数字是原始字节,对于 allocate
,它是该类型的 n*sizeof(T)
。那么 allocate
内部调用 malloc
吗?另外,从关于 allocate
:
的 cpp 参考
Allocates n * sizeof(T) bytes of uninitialized storage by calling
::operator new(std::size_t)
它调用 new
运算符。但据我所知, new
运算符不仅分配内存,而且 初始化 它与类型的构造函数,从 In what cases do I use malloc and/or new?:
The new keyword is the C++ way of doing it, and it will ensure that
your type will have its constructor called
但是引用声称它将return未初始化,仅分配内存,就像malloc
一样。所以问题也有点关于 new
,它是否也初始化(通过调用默认构造函数或原始类型的值初始化)或不初始化?并且 allocate
通过其实现调用 malloc
或者它如何请求 OS 原始内存块/
你对std::allocator<T>::allocate
的引用:
Allocates n * sizeof(T) bytes of uninitialized storage by calling ::operator new(std::size_t)
or ::operator new(std::size_t, std::align_val_t)
不引用由 c++ 运行时调用的 new
expression that creates and initializes objects. But to the operator new 以在 new
表达式的情况下分配内存。
默认运算符 new
在内部可能看起来像:
void* operator new(std::size_t sz) {
void *ptr = std::malloc(sz);
if (ptr)
return ptr;
else
throw std::bad_alloc{};
}
但那是 implementation-dependent,它可以在内部使用 OS 提供的任何方法来分配内存。对于嵌入式系统,它甚至可能是一个管理预分配内存的函数。
And does allocate calls malloc by its implementation or how does it requests OS for block of raw memory
这不能说是 implementation-dependent,但对于常见的实现,您可能会假设 malloc
和 allocate
在内部使用相同的系统调用,但是如果 allocate
das this 直接或间接使用 malloc
也依赖于实现。
我知道这两个函数都接受 size_t
数字。对于 malloc
,该数字是原始字节,对于 allocate
,它是该类型的 n*sizeof(T)
。那么 allocate
内部调用 malloc
吗?另外,从关于 allocate
:
Allocates n * sizeof(T) bytes of uninitialized storage by calling ::operator new(std::size_t)
它调用 new
运算符。但据我所知, new
运算符不仅分配内存,而且 初始化 它与类型的构造函数,从 In what cases do I use malloc and/or new?:
The new keyword is the C++ way of doing it, and it will ensure that your type will have its constructor called
但是引用声称它将return未初始化,仅分配内存,就像malloc
一样。所以问题也有点关于 new
,它是否也初始化(通过调用默认构造函数或原始类型的值初始化)或不初始化?并且 allocate
通过其实现调用 malloc
或者它如何请求 OS 原始内存块/
你对std::allocator<T>::allocate
的引用:
Allocates n * sizeof(T) bytes of uninitialized storage by calling
::operator new(std::size_t)
or ::operatornew(std::size_t, std::align_val_t)
不引用由 c++ 运行时调用的 new
expression that creates and initializes objects. But to the operator new 以在 new
表达式的情况下分配内存。
默认运算符 new
在内部可能看起来像:
void* operator new(std::size_t sz) {
void *ptr = std::malloc(sz);
if (ptr)
return ptr;
else
throw std::bad_alloc{};
}
但那是 implementation-dependent,它可以在内部使用 OS 提供的任何方法来分配内存。对于嵌入式系统,它甚至可能是一个管理预分配内存的函数。
And does allocate calls malloc by its implementation or how does it requests OS for block of raw memory
这不能说是 implementation-dependent,但对于常见的实现,您可能会假设 malloc
和 allocate
在内部使用相同的系统调用,但是如果 allocate
das this 直接或间接使用 malloc
也依赖于实现。