STD分配器是否会在堆上动态分配内存?它可以安全地删除内存吗?

Does the STD allocator dynamically allocate memory on the heap? does it safely delete memory?

本文关键字:内存 安全 删除 分配器 STD 动态分配 是否      更新时间:2023-10-16

因此,我正在尝试了解C 中的std::allocator<>,并从参考网站中感到困惑。尤其是因为我读取了分配器的构建体和解构方法,在C 17

中删除了

这是我写的以下代码

// Example with pointers and allocators
#include <iostream>
#include <memory>


int main()
{
  std::allocator<int> nums;
  int * first = nums.allocate(1); //is this on the heap, like with calling new int(4)?
  int * second = nums.allocate(2);
  *first = 7;
  second[0] = 2;
  second[1] = 4;
  std::cout << *first << std::endl;
  std::cout << second[1] << std::endl;
  nums.deallocate(first, 1); //is the int safely deleted from memory?
  nums.deallocate(second, 2);
}

当一个人调用分配方法时,返回的指针是在堆上返回到动态内存的点,还是分配的内存堆栈?

另外,当一个人调用DealLocate方法时,是否将指针从内存中删除?DealLocate等于delete

当一个人调用分配方法时,会在堆上返回到动态内存的指针

C 标准不使用单词 heap ,但是是的 std::allocator free Store 中分配,这通常称为堆,因为那是数据结构通常用于实现它。

当一个人调用DealLocate方法时,是否将指针从内存中删除?DealLaike等于delete

delete做了两件事:它称为对象的攻击子并处理内存。std::allocator::deallocate执行后一部分,仅执行后者。std::allocator::destroy执行前者。请注意,当记忆被交易时,未指定,只是它是。