为什么gcc缺乏在本地上下文中优化堆分配?

Den*_*ank 6 c++ optimization gcc

请考虑以下简化示例:

#include <utility>
#include <memory>

int test_lack()
{
    auto lam = []
    {
        return 10;
    };

    // move lam to the heap
    void* ptr = new decltype(lam)(std::move(lam));

    // retrieve the result of lam
    int res = (*static_cast<decltype(lam)*>(ptr))();

    if (ptr) // important
        delete static_cast<decltype(lam)*>(ptr);

    return res;
}
Run Code Online (Sandbox Code Playgroud)

GCC 5.2 -O3将其编译为:

test_lack():
  sub   rsp, 8
  mov   edi, 1
  call  operator new(unsigned long)
  mov   esi, 1
  mov   rdi, rax
  call  operator delete(void*, unsigned long)
  mov   eax, 10
  add   rsp, 8
  ret
Run Code Online (Sandbox Code Playgroud)

Clang 3.7 -O3将其优化为:

test_lack():
  mov   eax, 10
  ret
Run Code Online (Sandbox Code Playgroud)

为什么Clang能够优化给定代码而GCC失败?

是否有任何编译器标志或代码改进可以允许GCC对给定代码执行更积极的优化?


只是答案的一小部分:

GCC 5.2没有实现标准提案N3364,这意味着它不能像Clang那样优化对运营商的新调用.