Different behaviour of returning class object from a function

31 views Asked by At

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?

1

There are 1 answers

0
ravi On

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