stl里面的容器里的allocator是如何能够接管operator new的?

我们一般new一个对象,申请内存的过程是operator new完成的,那么stl中的allocator是如何接管operator new完成内存申请的工作呢?对象的内存申请权是如何转移的?我看stl里面也没有重载operator new呀,另外如果在栈上生成我们的stl对象,也会经过allocator吗?

阅读 3k
1 个回答

In the formal c++, there is no such term called STL, STL is never an abbreviation of Standard Library or Standard Template Library. You can also refer to another my answer here. Yes, Allocators were invented by Alexander Stepanov. But his original library has been out of date and some components are adopted by the standard library.

stl中的allocator是如何接管operator new完成内存申请的工作呢?对象的内存申请权是如何转移的?
all

From n4714 23.10.10.1 allocator members

[[nodiscard]] T* allocate(size_t n);
3 Remarks: the storage is obtained by calling ::operator new (21.6.2), but it is unspecified when or how often this function is called.

另外如果在栈上生成我们的stl对象,也会经过allocator吗?

There is no term stack in c++(only stack unwinding, which is not relevant here), in c, there is a term called activition record. Even if speaking to implementation, the choice of call stack or register should be decided by calling convention. No matter call stack or register, it will not invoke oeprator new function.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题