c++ – Destructor call and compiler optimizations


We all know that unused variables can be thrown away by the compiler, like the i variable below:

int main() {
  int a = 10;
  int i = 15;

  std::cout << a << std::endl;

  return 0;

I'm also interested in whether the compiler can call the destructor before the variable leaves the scope (for example, after its last use). Of particular interest is the following situation:

int foo() {
  static std::mutex mutex;
  ... some code ...

  return 0;

Tobish: is it possible, in this case, that the mutex will be released before the function exits?



"If a variable with an automatic storage class has an initialization or a destructor with side effects, the implementation has no right to destroy it before reaching the end of its block , nor to completely remove it during optimization, even if the variable appears to be unused; except that copy/move class object can be eliminated according to the rules of [class.copy.elision]"

Of course, this is a rule of the Abstract C++ Machine, which can be bypassed under the "as if" rule, but not in such cases. The implementation is well aware that interaction with the synchronization object can affect the observed behavior of the program.

Scroll to Top