1

The following code

class Foo
{
public:
    Foo() {a = 1;};
    Foo(const Foo&) :a(2) {};
    int a;
};

Foo foo()
{
    Foo a;
    return a; 
}

int main(int argc, char* argv[])
{
    Foo f = foo();
    std::cout << f.a << std::endl;

    return 0;
}

works different on Mac(with g++) and VS2013. On Mac it prints 1, whereas on Windows prints 2. Then why doesn't the program call the copy constructor when foo() returns a class object by value?

beaver
  • 550
  • 1
  • 9
  • 23
  • Turn on optimizations with VS2013, and you'll see the same result you got with g++ (and neither result is wrong, as I'm sure an answer will make clear). – Benjamin Lindley Apr 22 '15 at 12:35

1 Answers1

0

This behavior is due to extra copy being elided in MAC. Probably, turning on optimizations in Visual studio would bring similar results.

ravi
  • 10,994
  • 1
  • 18
  • 36