Search code examples
c++dynamicstandardsnew-operatorallocation

Does the C++ standard guarantee that dynamic allocations are done with new?


simple learning question. Is it specified in the C++ standard how std classes allocate memory? I would assume that internally, all allocations are at some point forwarded to new / new[]. I'm especially interested in allocations done by containers, std::function and lambdas.


Solution

  • Standard library containers

    Standard library containers take an allocator template argument that is used to control how memory is allocated. By default, they use std::allocator<T>. std::allocator<T> has a member function std::allocator<T>::allocate() that:

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

    Likewise, there is a std::allocator<T>::deallocate() function that calls operator delete(void *).

    std::function

    std::function has several constructors, some of which allow you to specify an allocator object to use for its internal allocations. If you don't specify one, then it will use std::allocator.

    Lambdas

    I'm not sure what allocations you expect to be done with lambdas. When you declare a lambda, the compiler synthesizes an unnamed functor type behind the scenes that implements the lambda in its operator(). If you capture any variables from the local scope, those variables simply become part of that type's definition, increasing the size of the lambda type, but there isn't any dynamic allocation required; the captured variables are just members of the lambda's unnamed type. If you were to assign the lambda to something like a std::function, then there could be dynamic allocation done by the std::function to accommodate the lambda's increased size.