0

I wrote the following code:

#include <iostream>
using namespace std;

class A
{
    int i;
public:
    A(int ii = 0) : i(ii) {}
    A(const A& a)
    {
        i = a.i + 1;
        cout << i << endl;
    }
};

A f(A a)
{
    A a2 = a;
    return a2;
}

int main()
{
    A a1;
    A a2;
    a2 = f(a1);
    return 0;
}

compiling this with g++ (no additional flags, same result if I add the -O0 flag) and running results:

1
2

compiling in VS2010 pro resulted:

1
2
3

what's going on here?

elyashiv
  • 3,623
  • 2
  • 29
  • 52
  • Copy elision. http://stackoverflow.com/questions/2143787/what-is-copy-elision-and-how-does-it-optimize-the-copy-and-swap-idiom – PaulMcKenzie Feb 19 '14 at 20:29
  • Never write a copy constructor or operator= to do anything other than copy and assign, because the compiler is allowed to assume how they act. – Zan Lynx Feb 19 '14 at 20:33
  • @PaulMcKenzie According to the link it's an optimization, but I get the same result when I use the `-O0` flag. – elyashiv Feb 19 '14 at 20:35
  • Compilers tend to apply this optimization always, regardless of optimization level, because it changes the observable behaviour of a program, and the observable behaviour of a correct program shouldn't depend on optimization level. – juanchopanza Feb 19 '14 at 20:38

0 Answers0