Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 385
BeeOnRope Avatar asked Oct 19 '17 05:10

BeeOnRope


2 Answers

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.

like image 118
Brian Bi Avatar answered Sep 30 '22 02:09

Brian Bi


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)

like image 25
R Sahu Avatar answered Sep 30 '22 04:09

R Sahu