I played around with Godbolt\'s CompilerExplorer. I wanted to see how good certain optimizations are. My minimum working example is:
#include
int
N3664's change to [expr.new], cited in one answer and one comment, permits new-expressions to not call a replaceable global allocation function. But vector
allocates memory using std::allocator
, which calls ::operator new
directly, not via a new-expression. So that special permission doesn't apply, and generally compilers cannot elide such direct calls to ::operator new
.
All hope is not lost, however, for std::allocator
's specification has this to say:
Remarks: the storage is obtained by calling
::operator new
, but it is unspecified when or how often this function is called.
Leveraging this permission, libc++'s std::allocator
uses special clang built-ins to indicate to the compiler that elision is permitted. With -stdlib=libc++
, clang compiles your code down to
foo(): # @foo()
mov eax, 5
ret