The following code
int foobar() {
int* i = new int;
return *i;
}
compiles in Clang 5.0.0 on x86-64 with -03 to
foobar(): # @foobar()
ret
(https://godbolt.org/g/uCHVo8)
I understand why it can just return an undefined value (since new'ing it returns an undefined value). But why is clang allowed to optimize away the new operator altogether; does that not change the behaviour of the code?
For example in this case:
static int foobar() {
int* i = new int;
return *i;
}
int main(int argc, char** argv) {
int i = 0;
try {
for (;;) i += foobar();
}
catch (...) {}
return i;
}
Clang generates:
main: # @main
.LBB0_1: # =>This Inner Loop Header: Depth=1
jmp .LBB0_1
GCC on the other hand does more work, but at least it does some alloc (?) in the operator new:
main:
push rbx
xor ebx, ebx
.L2:
mov edi, 4
call operator new(unsigned long)
add ebx, DWORD PTR [rax]
jmp .L2
mov rdi, rax
call __cxa_begin_catch
call __cxa_end_catch
mov eax, ebx
pop rbx
ret
a) Which compiler is right? b) Bug in Clang?