【发布时间】:2017-11-28 05:49:29
【问题描述】:
所以我正在尝试了解 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);
}
当调用 allocate 方法时,返回的指针是指向堆上的动态内存块还是分配的内存堆栈?
另外,当调用 deallocate 方法时,被释放的指针是否也会从内存中删除它的对象?是否等同于delete?
【问题讨论】:
-
如果您阅读例如this
allocatereference 你会看到它使用了::operator new,它根据to this reference 从 free store 分配,这是堆的标准名称。 -
thx,但它是否也会在调用 deallocate 时删除内存及其指向的对象?
-
现在您已经获得了分配器参考页面的链接,尝试阅读它并自己弄清楚如何,如果您不这样做,请询问后续问题不明白什么?学习如何阅读和理解技术文档是每个 C++ 开发人员必备的技能。
-
我已经阅读了链接的文档,并且我知道 new 和 delete 都是用 allocate 和 deallocate 调用的。让我困惑的是
Calls ::operator delete(void*), but it is unspecified when and how it is called. -
在您被第一条评论引导到的页面底部有一条注释,它正好解决了这个问题。
标签: c++ c++11 memory-management