Jul 5, 2011 at 6:45am UTC
I got other output from what i expected:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#include <iostream>
class Foo
{
public :
int data0;
int data1;
Foo(int d0, int d1) : data0(d0), data1(d1)
{
std::cout << "Foo(int,int)" << std::endl;
}
Foo(const Foo& o) : data0(o.data0), data1(o.data1)
{
std::cout << "Foo(const Foo&)" << std::endl;
}
};
int main()
{
Foo f(Foo(5, 7));
std::cout << "Press enter to exit..." ;
std::cin.get();
return 0;
}
output:
expected output:
Foo(int,int)
Foo(const Foo&)
???
Last edited on Jul 5, 2011 at 6:46am UTC
Jul 5, 2011 at 7:34am UTC
I would guess that the compiler optimized away the temporary created by the inner call to the constructor.
Jul 5, 2011 at 7:38am UTC
I think that the compiler is optimizing the statement
Foo f(Foo(5,7))
to
Foo f(5,7)
In this case if you can dump the assembly code, you might find that no temporary object is generated at all.
Jul 5, 2011 at 7:46am UTC
Indeed, this is a type of copy elision explicitly allowed by the C++ standard, similar to NRVO.
Jul 5, 2011 at 8:04am UTC
Ok, thanks. This is the first time i heard of this.
In what circumstances this won't work? I want to know when i can rely on this feature.
Jul 5, 2011 at 10:21am UTC
There are compiler options to disable the copy elision, once you do that then you can be pretty sure about your code. For g++ we have this option "-fno-elide-constructors".