Why isn't this unused variable optimised away?

后端 未结 4 1652
情深已故
情深已故 2021-02-06 21:47

I played around with Godbolt\'s CompilerExplorer. I wanted to see how good certain optimizations are. My minimum working example is:

#include 

int         


        
4条回答
  •  生来不讨喜
    2021-02-06 22:26

    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::allocate, 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::allocate'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
    

提交回复
热议问题