I have just discovered something which has surprised me. In the code
below the copy constructor never gets called!
class Foo
{
public:
Foo() { printf("constructor\n",this); }
Foo(const Foo& copy) { printf("copy constructor\n"); }
Foo& operator=(const Foo& copy) { printf("operator=\n"); }
~Foo() { printf("destructor\n"); }
};
// Note. getFoo is defined in another translation unit (ie. not inline)
Foo getFoo()
{
printf("2\n");
Foo f;
printf("3\n");
return f;
}
void doSomething()
{
printf("1\n");
Foo myfoo(f);
printf("4\n");
}
Output:
> 1
> 2
> constructor
> 3
> 4
> destructor
It looks like it optimises the temporary out. I would have expected to
see a constructor followed by a copy constructor, and then 2 destructors.
Is there any way to force the copy constructor to be called in the
assignment of myfoo to getFoo()? I have a case where it is vital that
the copy constructor is run in this instance as the the temporary (f)
references data which goes out of scope in getFoo() and so myfoo has
references to already released memory - the copy constructor deals with
this elegantly.