Question: Original code

```
#include <iostream>
int global;
struct A
{
   A(){}
   A(const A&x){
       ++global;
   }
   ~A(){}
};
A foo()
{  
     A a;
     return a;  
}
int main()
{
   A x = foo();
   std::cout << global;
}

```

Output would be `0` on an optimized compiler supporting Named Return Value Optimization.

When I change the definition of `foo` to

```
A foo()
{ 
  { 
     A a;
     return a;  
  }
}

```

I get `1` as the output i.e copy c-tor gets called once. What could be the possible reason? Introducing a dummy scope changes the behavior of the code completely. What am I missing?

I tested it on g++ compiler. Any compiler guy around here who can explain the scenario in some implementation-specific manner?

**EDIT**

I tested it on clang and it optimizes the call to the copy c-tor even in the second case.

Andrew Pinski (gcc guy) confirmed that this is indeed a case of missed optimization on g++.

Answer: 
I don't see any reason other than that the compiler is not being smart enough to see that the dummy scope (introduced by extra brackets) makes no difference at all, at least for this particular code. The compiler is being fooled by the extra brackets; it *probably* made the wild assumptions about the rest of the function body (which doesn't even exist).

Zero or 1, either way the behavior is completely Standard comformant, as the Standard doesn't *require* the compiler to produce `0` (or `1` for that matter). So it is upto the compiler, as you already know. 

As for the assembly code generated for `foo` in both cases has just one little difference:

* First code:

```
__Z3foov:
LFB992:
     .cfi_startproc
     movl  4(%esp), %eax
     ret   $4
     .cfi_endproc

```
* Second code:

```
__Z3foov:
LFB992:
     .cfi_startproc
     incl _global      <----- incrementing the global. God knows why!
     movl  4(%esp), %eax
     ret   $4
     .cfi_endproc

```

I used `g++ -O6`. Version : `MinGW (GCC) 4.6.1`
There will be a copy as you return by value. Optimizing settings can (should) never change the visible behaviour of a program.