Consider the following simplified example:
#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;
}
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
Clang 3.7 -O3 optimizes this into:
test_lack():
mov eax, 10
ret
Why is Clang capable of optimizing the given code whereas GCC fails?
Are there any compiler flags or code improvements which could allow GCC to perform more aggressive optimization to the given code?
Just a short addition to the answer:
GCC 5.2 doesn't implement standard proposal N3364 which means it can't optimize the given call to operator new out like Clang does it.