Is it guaranteed that C++ standard library containers call the replaceable new functions?

不问归期 提交于 2019-12-30 17:22:06

问题


If I replace all the operator new signatures that I can, at least on the implementations I have tested, I see that the standard containers call into my replaced versions to allocate memory.

Is this guaranteed by the standard? That is, would it be illegal for an implementation to use an optimized version which didn't call my replacement functions for the memory underlying the standard containers?


回答1:


The default allocator for allocator-aware containers such as std::vector<T> is std::allocator<T>. This class template is described in section [default.allocator] of the standard. According to [allocator.members]/6 in C++14:

the storage is obtained by calling ::operator new(std::size_t)

So the global operator new is the one that you need to replace. If you overloaded operator new specifically for T, that overload will not be used by the default allocator.




回答2:


Is this guaranteed by the standard?

As long as you don't use a custom allocator to create an instance of a container, I believe that is true.

From http://en.cppreference.com/w/cpp/memory/allocator

The std::allocator class template is the default Allocator used by all standard library containers if no user-specified allocator is provided.

and

From http://en.cppreference.com/w/cpp/memory/allocator/allocate:

Allocates n * sizeof(T) bytes of uninitialized storage by calling ::operator new(std::size_t)



来源:https://stackoverflow.com/questions/46823224/is-it-guaranteed-that-c-standard-library-containers-call-the-replaceable-new-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!