1

Given a program:

#include <cstdlib>
#include <memory>

bool test() {
  int* ptr = (int *)malloc(sizeof(int));
  bool result = ptr != nullptr;
  free(ptr);
  return result;
}

bool test2() noexcept {
  int * ptr;
  try {
    ptr = new int;
  }
  catch (const std::bad_alloc&) {
    return false; 
  }
  bool result = ptr != nullptr;
  delete ptr;
  return result;
}

int main()
{
  return test();
}

Clang optimizes both functions to simple

{
  return true;
}

See on godbolt. GCC 6.1 does not do this. Clang do this even with -O1 level of optimization.

Is it legal in terms of C++ Standard?

5
  • Looks valid to me under "as-if" rule. I don't see how a conforming program can detect whether this optimization has taken place. Jul 17, 2016 at 18:20
  • @IgorTandetnik Question not about how to detect it. Question is about is it standard conformant to do such an optimization?
    – vladon
    Jul 17, 2016 at 18:22
  • 4
    But detecting is the crux of as-if rule: "[intro.execution]/1 The semantic descriptions in this International Standard define a parameterized nondeterministic abstract machine. This International Standard places no requirement on the structure of conforming implementations. In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below. 5)" Jul 17, 2016 at 18:26
  • "Footnote 5: This provision is sometimes called the “as-if” rule, because an implementation is free to disregard any requirement of this International Standard as long as the result is as if the requirement had been obeyed, as far as can be determined from the observable behavior of the program. For instance, an actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no side effects affecting the observable behavior of the program are produced." Emphasis mine. Jul 17, 2016 at 18:26
  • 1
    @IgorTandetnik it could detect it if you replace global operator new. But I think, this is not the case in provided code. OP should replace it with function with side effects and check optimisations again. Jul 17, 2016 at 18:30

0

Browse other questions tagged or ask your own question.